fopen function-open file
You can use the fopen function to open a file. You can use it by reading the stdio.h header.
FILE * fopen (const char * file_name, const char * mode);
The first argument is the filename of the file you want to open. The second argument is the mode. If the file is opened successfully, a value of "FILE * type" representing the file stream is returned.
List of modes
A list of modes.
Mode | Behavior |
---|---|
r | Read (error if there is no file) |
w | Write (create new if there is no file) |
a | Additional write (create new if there is no file) |
r + | Read and write (error if there is no file) |
w + | Read and write (create new if there is no file) |
a + | Read and add write (create new if there is no file) |
Writing means that the contents of the file are cleared and you are writing with new contents. Additional write means to add to the end of the file and write.
The above modes can be combined with "b" which means binary mode.
br bw
The default behavior is to open in text mode, and in the case of Windows, the line feed characters "CR" and "LF" contained in the file are replaced with "\ n".
In binary mode, this replacement is not possible.
sample fopen function
This is a sample of the fopen function.
Read the file
The fopen function opens the file in read mode, the fgetc function reads it, and outputs it to standard output.
#include <stdio.h> #include <stdlib.h> int main (void) { // Open the file in read mode const char * in_file = "input.txt"; FILE * in_fp = fopen (in_file, "r"); if (in_fp == NULL) { fprintf (stderr, "Can't open file%s\n", in_file); exit (1); } // Read and output to standard output int32_t ch; while (ch = fgetc (in_fp)) { if (ch == EOF) { break; } fputc (ch, stdout); } // write to file const char * message = "Hello"; fprintf (in_fp, "%s\n", message); // Close the file with the fopen function fclose (in_fp); }
It is an input file "input.txt".
Hello World!
This is the output result.
Hello World!
Write to file
Open the file in write mode with the fopen function, write the contents with the fprintf function, and use the fclose function. closes the file.
#include <stdio.h> #include <stdlib.h> int main (void) { // Open the file in write mode const char * out_file = "output.txt"; FILE * out_fp = fopen (out_file, "w"); if (out_fp == NULL) { fprintf (stderr, "Can't open file%s\n", out_file); exit (1); } // write to file const char * message = "Hello"; fprintf (out_fp, "%s\n", message); // Close the file with the fopen function fopen (out_fp); }