C:fopen
lastmod 2026-02-26created 2016-12-0510 edits
Mode
| MODE | Read | Write | Create |
| r | Yes | No | No (error if missing) |
| w | No | Yes | Yes (contents removed if it exists) |
| a | No | Yes (ONLY APPEND) | Yes |
| r+ | Yes | Yes | No (error if missing) |
| w+ | Yes | Yes | Yes (contents removed if it exists) |
| a+ | Yes | Yes (ONLY APPEND) | Yes |
-
+is update mode. This mode opens the stream for both input and output. -
bselects binary mode. This flag is effective on Windows. -
tselects text mode. This flag is effective on Windows. -
x
Combinations:
-
r- Read in text mode. -
w- Write in text mode. Creates the file if it does not exist; if it exists, deletes the existing contents and replaces them with the new contents. -
a- Write in text mode. Creates the file if it does not exist; if it exists, continues writing from the very end of the file. -
rb- Read in binary mode. -
wb- Write in binary mode. Creates the file if it does not exist; if it exists, deletes the existing contents and replaces them with the new contents. -
ab- Write in binary mode. Creates the file if it does not exist; if it exists, continues writing from the very end of the file. -
r+- Read and write in text mode. -
w+- Read and write in text mode. Creates the file if it does not exist; if it exists, deletes the existing contents and replaces them with the new contents. -
a+- Read and write in text mode. Creates the file if it does not exist; if it exists, continues writing from the very end of the file. -
rb+- Read and write in binary mode. -
wb+- Read and write in binary mode. Creates the file if it does not exist; if it exists, deletes the existing contents and replaces them with the new contents. -
ab+- Read and write in binary mode. Creates the file if it does not exist; if it exists, continues writing from the very end of the file.
Simple example
#include <stdio.h>
#include <string.h>
int main()
{
FILE * f = fopen("test", "w+");
if (f == 0) {
printf("File open error.\n");
return 1;
}
char const * str = "TEST";
fwrite(str, sizeof(char), strlen(str), f);
fseek(f, 0, SEEK_SET);
char buffer[100] = {0,};
int size = fread(buffer, sizeof(char), 4, f);
printf("Result(%d) %s\n", size, buffer);
fclose(f);
return 0;
}