C programming - File input/output (I/O)
In C programming, files input/output (I/O) refers to the process of reading and writing data to and from external files. C provides several functions and libraries for performing file I/O operations, including the stdio.h library.
The basic steps for performing file I/O in C programming are:
- Opening a file: To read or write data from a file, we must first open the file. We can use the
fopen()function to open a file in C. The syntax of thefopen()function is as follows:
FILE *fopen(const char *filename, const char *mode);
The filename parameter is a string that represents the name of the file we want to open, and the mode parameter is a string that specifies the mode in which we want to open the file (read, write, append, etc.).
For example, to open a file named "data.txt" in read mode, we can write:
FILE *fp = fopen("data.txt", "r");
- Reading from a file: Once we have opened a file, we can read data from the file using the
fscanf()function. Thefscanf()function reads data from a file in the same way asscanf()reads data from the standard input. The syntax of thefscanf()function is as follows:
int fscanf(FILE *stream, const char *format, ...);
The stream parameter is a pointer to the file we want to read from, and the format parameter is a string that specifies the format of the data to be read.
For example, to read an integer value from a file, we can write:
int num; fscanf(fp, "%d", &num);
- Writing to a file: To write data to a file, we can use the
fprintf()function. Thefprintf()function writes data to a file in the same way asprintf()writes data to the standard output. The syntax of thefprintf()function is as follows:
int fprintf(FILE *stream, const char *format, ...);
The stream parameter is a pointer to the file we want to write to, and the format parameter is a string that specifies the format of the data to be written.
For example, to write a string to a file, we can write:
fprintf(fp, "Hello, World!\n");
- Closing a file: Once we have finished reading from or writing to a file, we must close the file using the
fclose()function. Thefclose()function closes the file and frees up any system resources associated with the file. The syntax of thefclose()function is as follows:
int fclose(FILE *stream);
The stream parameter is a pointer to the file we want to close.
For example, to close a file, we can write:
fclose(fp);
