What is file pointer in C?

C Programming Language >   Pointer in C Language >   Pointer in C  

Short Question

28025


Answer:

  • File pointer is a pointer which is used to handle and keep track on the files being accessed. A new data type called “FILE” is used to declare file pointer. This data type is defined in stdio.h file. File pointer is declared as FILE *fp. Where, ‘fp’ is a file pointer.
  • fopen() function is used to open a file that returns a FILE pointer. Once file is opened, file pointer can be used to perform I/O operations on the file. fclose() function is used to close the file.

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 <stdio.h>

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.


This Particular section is dedicated to Question & Answer only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.