How is fdopen as open with the same mode and flags?

I would like to have type FILE* for using fprintf . I need to use fdopen to get FILE* instead of open , which returns an int . But can we do the same with fdopen and open ? (I never used fdopen )

I would like to make fdopen which does the same thing:

 open("my_file", 0_CREAT | O_RDWR | O_TRUNC, 0644); 
+4
source share
3 answers

fdopen accepts a file descriptor that may be previously returned by open , so this is not a problem.

Just open your file will receive a descriptor, and then fdopen this descriptor.

fdopen simply creates a user-buffered stream using any descriptor that supports read and write operations.

+7
source

fdopen() use a file descriptor for a file pointer:

The fdopen() function associates a stream with a file descriptor. File descriptors are obtained from open() , dup() , creat() or pipe() , which open files but do not return pointers to the stream of the FILE structure. Streams are required for almost all stdio library routines.

 FILE* fp = fdopen(fd, "w"); 

this sample code can help you more since you want to use fprintf() :

 int main(){ int fd; FILE *fp; fd = open("my_file",O_WRONLY | O_CREAT | O_TRUNC); if(fd<0){ printf("open call fail"); return -1; } fp=fdopen(fd,"w"); fprintf(fp,"we got file pointer fp bu using File descriptor fd"); fclose(fp); return 0; } 

Note:

+7
source

If you have not previously used a file descriptor for your file, rather use fopen .

 FILE* file = fopen("pathtoyourfile", "w+"); 

Note that fopen uses stand-library-calls, not system calls (open). Thus, you do not have many parameters (for example, specifying access control values).

See the man page .

+1
source

All Articles