Duplicating file pointers?

2019-01-24 03:21发布

Just a quick question: Is there a way to duplicate a file pointer (those returned by fopen()), similar to how dup() duplicates a file handlers returned by functions like open()?

Basically, I want to be able to do something like this:

FILE *fp = fopen("some_file", "r");
FILE *fp2 = /* do something to duplicate the file pointer */;
fclose(fp); // fp2 is still open
/* do something with fp2 */
fclose(fp2);

标签: c file-io
3条回答
Melony?
2楼-- · 2019-01-24 03:45
FILE *fp2 = fdopen (dup (fileno (fp)), "r");
查看更多
Animai°情兽
3楼-- · 2019-01-24 03:53

I opened twice the same file and assigned two pointers and in the end closed both separately. In my case I had to show the content in a text window using one pointer and process the data in file using the other pointer. e.g.

//define global variables

FILE *fp1 = fopen("some_file", "r");

//fp1 used in functioncall to display textbuffer 

fclose(fp1); 

//fp2 used in functioncall to process data 

fclose(fp2);
查看更多
仙女界的扛把子
4楼-- · 2019-01-24 03:54

You could use fileno to get a descriptor for a FILE*, dup that, and then use fdopen to get a new FILE* from the new descriptor.

查看更多
登录 后发表回答