Syntax
#include <stdio.h> FILE *fdopen(int handle, char *type);Description
fdopen associates an input or output stream with the file identified by handle. The type variable is a character string specifying the type of access requested for the stream.
Mode
Warning: Use the w, w+, wb, wb+, and w+b modes with care; they can destroy existing files.
The specified type must be compatible with the access mode you used to open the file. If the file was opened with the O_APPEND FLAG, the stream mode must be r, a, a+, rb, ab, a+b, or ab+.
When you open a file with a, a+, ab, a+b, or ab+ as the value of type, all write operations take place at the end of the file. Although you can reposition the file pointer using fseek or rewind, the file pointer always moves back to the end of the file before the system carries out any write operation. This action prevents you from writing over existing data.
When you specify any of the types containing +, you can read from and write to the file, and the file is open for update. However, when switching from reading to writing or from writing to reading, you must include an intervening fseek, fsetpos, or rewind operation. You can specify the current file position with fseek.
In accessing text files, carriage-return line-feed (CR-LF) combinations are translated into a single line feed (LF) on input; LF characters are translated to CR-LF combinations on output. Accesses to binary files suppress all of these translations. (See "Stream Processing" in the VisualAge C++ Programming Guide for the differences between text and binary streams.)
If fdopen returns NULL, use close to close the file. If fdopen is successful, you must use fclose to close the stream and file.
fdopen returns a pointer to a file structure that can be used to access the open file. A NULL pointer return value indicates an error.
This example opens the file sample.dat and associates a stream with the file using fdopen. It then reads from the stream into the buffer.
#include <io.h>#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> int main(void) { long length; int fh; char buffer[20]; FILE *fp; memset(buffer, '\0', 20); /* Initialize buffer*/ printf("\nCreating sample.dat.\n"); system("echo Sample Program > sample.dat"); if (-1 == (fh = open("sample.dat", O_RDWR|O_APPEND))) { perror("Unable to open sample.dat"); return EXIT_FAILURE; } if (NULL == (fp = fdopen(fh, "r"))) { perror("fdopen failed"); close(fh); return EXIT_FAILURE; } if (7 != fread(buffer, 1, 7, fp)) { perror("fread failed"); fclose(fp); return EXIT_FAILURE; } printf("Successfully read from the stream the following:\n%s.\n", buffer); fclose(fp); return 0; /**************************************************************************** The output should be: Creating sample.dat. Successfully read from the stream the following: Sample . ****************************************************************************/ }Related Information