C examples for stdio.h:fopen
function
<cstdio> <stdio.h>
Open file with filename and open mode
FILE * fopen ( const char * filename, const char * mode );
Parameter | Description |
---|---|
filename | C string containing the file name . |
mode | C string containing a file access mode. |
mode value can be:
Value | Action | Description |
---|---|---|
"r" | read | Open file for reading. The file must exist. |
"w" | write | Create an empty file for writing. If the file already exists, empty the existing file. |
"a" | append | Open file for appending. The file is created if it does not exist. |
"r+" | read/update | Open a file both for input and output. The file must exist. |
"w+" | write/update | Create an empty file and open it both for input and output. If the file already exists, empty the existing file. |
"a+" | append/update | Open a file both for input and output, append to the end of the file. The file is created if it does not exist. |
With the mode specifiers above the file is open as a text file.
In order to open a file as a binary file, a "b" character has to be included in the mode string.
This additional "b" character can either be appended at the end of the string.
It makes the following compound modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or ("rb+", "wb+", "ab+").
Legal Values for the mode Parameter of fopen( ) to work on text or binary file
Mode | Meaning |
---|---|
"r" | Open text file for reading |
"w" | Create a text file for writing |
"a" | Append to text file |
"rb" | Open binary file for reading |
"wb" | Create binary file for writing |
"ab" | Append to a binary file |
"r+" | Open text file for read/write |
"w+" | Create text file for read/write |
"a+" | Open text file for read/write |
"rb+" or "r+b" | Open binary file for read/write |
"wb+" or "w+b" | Create binary file for read/write |
"ab+" or "a+b" | Open binary file for read/write |
On success, the function returns a pointer to a FILE object.
Otherwise, a null pointer is returned.
The correct method of opening a file is illustrated by this code fragment:
FILE *fp; if ((fp = fopen("test", "w"))==NULL) { printf("Cannot open file.\n"); exit(1); }
This fragment opens a file called TEST for binary read/write operations:
FILE *fp; if((fp=fopen("test", "rb+"))==NULL) { printf("Cannot open file.\n"); exit(1); }
#include <stdio.h> int main ()/*from ww w. ja v a 2s .c o m*/ { FILE * pFile; pFile = fopen ("main.cpp","w"); if (pFile==NULL){ perror ("Error opening file"); return -1; } fputs ("fopen example",pFile); fclose (pFile); return 0; }