Files Input/Output in C language
File input/output (I/O) is the process of reading and writing data to and from files. In C programming language, file I/O operations are performed using standard library functions like fopen(), fclose(), fread(), fwrite(), fscanf(), and fprintf().
Example:
#include <stdio.h>
int main() {
FILE *fp;
char buffer[100];
// Open file for writing
fp = fopen("myfile.txt", "w");
if (fp == NULL) {
printf("Error: cannot open file\n");
return -1;
}
// Write data to the file
fprintf(fp, "Hello World\n");
fputs("This is some text\n", fp);
// Close the file
fclose(fp);
// Open file for reading
fp = fopen("myfile.txt", "r");
if (fp == NULL) {
printf("Error: cannot open file\n");
return -1;
}
// Read data from the file and print it to the console
while (fgets(buffer, 100, fp) != NULL) {
printf("%s", buffer);
}
// Close the file
fclose(fp);
return 0;
}
Output:
Hello World
This is some text
In this example, we first open a file named myfile.txt for writing using the fopen() function. If the file cannot be opened, we print an error message and return an error code. We then use the fprintf() function to write the string “Hello World” to the file, and the fputs() function to write the string “This is some text” to the file. Finally, we close the file using the fclose() function.
Next, we open the same file for reading using the fopen() function with the “r” mode specifier. Again, if the file cannot be opened, we print an error message and return an error code. We then use the fgets() function to read data from the file into a character buffer, and print the buffer to the console using the printf() function. We repeat this process until the end of the file is reached. Finally, we close the file using the fclose() function.
This is a straightforward illustration of how to read and write data to a file in C using functions from the standard library. For more complex file I/O operations, there are a variety of different functions and modes that can be employed.