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:

  1. 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 the fopen() function is as follows:
ref‮re‬ to:theitroad.com
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");
  1. Reading from a file: Once we have opened a file, we can read data from the file using the fscanf() function. The fscanf() function reads data from a file in the same way as scanf() reads data from the standard input. The syntax of the fscanf() 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);
  1. Writing to a file: To write data to a file, we can use the fprintf() function. The fprintf() function writes data to a file in the same way as printf() writes data to the standard output. The syntax of the fprintf() 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");
  1. Closing a file: Once we have finished reading from or writing to a file, we must close the file using the fclose() function. The fclose() function closes the file and frees up any system resources associated with the file. The syntax of the fclose() 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);