File Input/Output in C

File input/output (I/O) in C involves reading from and writing to files. The standard C library provides a set of functions for file I/O operations. In general, file I/O involves the following steps:

1. Open the file: To read from or write to a file, it must be opened using the `fopen()` function. The function takes two arguments: the name of the file to be opened and the mode in which the file is to be opened (read, write, or append). If the file cannot be opened, the function returns a `NULL` pointer.

2. Read from the file: To read data from a file, you can use the `fread()` or `fgets()` function. The `fread()` function reads a specified number of bytes from the file, while the `fgets()` function reads a line of text from the file. Both functions return a pointer to the data that was read.

3. Write to the file: To write data to a file, you can use the `fwrite()` or `fprintf()` function. The `fwrite()` function writes a specified number of bytes to the file, while the `fprintf()` function writes formatted data to the file. Both functions return the number of bytes or characters written to the file.

4. Close the file: Once you are done reading from or writing to the file, it must be closed using the `fclose()` function. This ensures that any pending data is written to the file and any resources used by the file are released.

Here are some examples of file I/O in C:

1. Reading from a file using `fread()`:

FILE *fp;
char buffer[100];
fp = fopen("myfile.txt", "rb");
fread(buffer, sizeof(char), 100, fp);
fclose(fp);

This code opens a file named “myfile.txt” for reading in binary mode, reads 100 bytes of data from the file into a character buffer, and then closes the file.

2. Writing to a file using `fwrite()`:

FILE *fp;
int data[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
fp = fopen("myfile.txt", "wb");
fwrite(data, sizeof(int), 10, fp);
fclose(fp);

This code opens a file named “myfile.txt” for writing in binary mode, writes an array of 10 integers to the file, and then closes the file.

3. Reading from a file using `fgets()`:

FILE *fp;
char buffer[100];
fp = fopen("myfile.txt", "r");
fgets(buffer, 100, fp);
fclose(fp);

This code opens a file named “myfile.txt” for reading in text mode, reads a line of text from the file into a character buffer, and then closes the file.

4. Writing to a file using `fprintf()`:

FILE *fp;
int num = 42;
fp = fopen("myfile.txt", "w");
fprintf(fp, "The answer is %d", num);
fclose(fp);

This code opens a file named “myfile.txt” for writing in text mode, writes a formatted string to the file that includes the value of the `num` variable, and then closes the file.

It’s important to note that when using file I/O functions in C, you should always check the return values to ensure that the operations were successful, and to handle any errors appropriately.