What is the usage of fopen in the C language?
In C language, the fopen function is used to open a file and returns a file pointer pointing to that file. The prototype of the fopen function is as follows:
FILE *fopen(const char *filename, const char *mode);
In this case, filename refers to the path and name of the file to be opened, while mode represents the opening mode of the file. Some commonly used file opening modes include:
- “r”: Read-only mode, the file must exist, and if it does not, it will return NULL.
- “w” mode: Writing mode, create a new file if it does not exist, or truncate the file to 0 bytes if it already exists.
- Option:
“Option A: Append mode, create a new file if it does not exist, and writing will start from the end of the file.” - “r+”: This mode allows reading and writing in a file that must already exist.
- “w+” mode: Read and write mode, creates a new file if it doesn’t exist, truncates the file to 0 bytes if it does exist.
- “mode a+” allows for reading and writing, creates a new file if it doesn’t exist, and starts writing from the end of the file.
This is an example code:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
printf("File open error\n");
return 1;
}
fprintf(file, "Hello, World!");
fclose(file);
return 0;
}
In the code sample above, a file named example.txt was opened using write mode “w”, “Hello, World!” was written to the file, and then the file was closed.
More tutorials
Reading and Writing data using Python(Opens in a new browser tab)
What is the difference between fread and fwrite in C language?(Opens in a new browser tab)
Converting string to array in the Java programming language(Opens in a new browser tab)
Partition in Linux Step-by-Step Guide(Opens in a new browser tab)
Partition in Linux Step-by-Step Guide(Opens in a new browser tab)
convert string to character array in Java.(Opens in a new browser tab)