In C, a file pointer is a variable that is used to point to a specific location within a file. It is used to read from or write to a file. The stdio.h library provides functions for file I/O operations, and the FILE type is used to define a file pointer.
Here is an example that demonstrates the use of a file pointer to read and write to a file:
#include int main() { FILE *fp; char buffer[100]; // Open file for writing fp = fopen("test.txt", "w"); fprintf(fp, "This is written to the file.\n"); fclose(fp); // Open file for reading fp = fopen("test.txt", "r"); fscanf(fp, "%s", buffer); printf("Contents of file: %s\n", buffer); fclose(fp); return 0; }
In this example, a file pointer named fp is declared as a FILE type. The fopen() function is used to open the file named "test.txt" in write mode with the w mode argument. The fprintf() function is used to write a string to the file, and the fclose() function is used to close the file.
Next, the file is opened again using fopen() in read mode with the r mode argument. The fscanf() function is used to read the contents of the file into the buffer array. Finally, the contents of the buffer array are printed to the console using printf(), and the file is closed again using fclose().
When this program is run, it will write the string "This is written to the file." to the "test.txt" file, and then read the contents of the file and print them to the console.
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.