Make File
FILE *fp;
fp = fopen("data.txt", "r");
Once the file is open, you can use the fread and fwrite functions to read and write data, respectively. The fread function takes four arguments: a pointer to the buffer where the data will be stored, the size of each element, the number of elements to read, and a pointer to the file. For example, the following code reads 10 integers from the file:
C
int data[10];
fread(data, sizeof(int), 10, fp);
Similarly, the fwrite function takes four arguments: a pointer to the data to be written, the size of each element, the number of elements to write, and a pointer to the file. For example, the following code writes 10 integers to the file:
C
int data[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
fwrite(data, sizeof(int), 10, fp);
When you're done working with a file, it's important to close it using the fclose function. This releases the resources that the file was using and prevents any potential errors or data corruption. For example, the following code closes the file that was opened earlier:
SCSS
fclose(fp);
It's also important to note that C provides a set of functions to perform formatted input and output operations on files, such as fprintf and fscanf. These functions work in a similar way as the printf and scanf functions but take a file pointer as an additional parameter.
In conclusion, file I/O is an essential concept in programming, and C provides a set of functions for working with files, allowing you to easily read and write data to and from files. Understanding how to open, read, write, and close files is essential for many types of programming projects, and it is a fundamental concept that every C programmer should know. It's also important to keep in mind that when working with files, it's important to close the file after you've finished reading or writing to it to release the resources and prevent any errors or data corruption.