C File Input and Output Functions
Syntax
C file input and output functions follow a common syntax:
FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *stream);
// and others such as:
int fprintf(FILE *stream, const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);
char *fgets(char *s, int size, FILE *stream);
Example
#include <stdio.h>
int main() {
FILE *fp;
char c = 'A';
fp = fopen("test.txt", "w+");
fprintf(fp, "%c", c);
rewind(fp);
fscanf(fp, "%c", &c);
printf("The character read from the file is %c\n", c);
fclose(fp);
return 0;
}
Output
The output of the above example is:
The character read from the file is A
Explanation
C file input and output functions provide a way to read and write data to files on a computer's hard drive. These functions can be very useful when creating applications that require saving data to a file or reading data from a file.
The fopen
function is used to open a file and returns a FILE*
pointer, which is used to access the file. The first argument is a string that contains the name of the file and the second argument is a string that contains the mode in which we want to open the file.
The fprintf
function is used to write data to the file. The first argument is the FILE*
pointer, the second argument is the format string and the rest of the arguments are the values to be formatted.
The fscanf
function is used to read data from the file. The first argument is the FILE*
pointer, the second argument is the format string and the rest of the arguments are pointers to where the values are to be stored.
The fclose
function is used to close the file.
Use
C file input and output functions are primarily used for reading and writing data to files. It is also useful for saving and loading states in games, storing logs, and serializing data.
Important Points
- Always ensure that a file is opened before accessing it.
- Always check the return value of
fopen
to ensure that the file was opened successfully. - Close the file after accessing it to release system resources.
- Double check that you have permission to read and write to a file before using it.
Summary
C file input and output functions provide powerful tools for handling file input and output operations. Understanding how to open, read, write, and close a file is important in developing robust applications that can persist data. It is important to keep in mind that file operations can be slow, so it is best to use them only when necessary.