In C programming language, a file pointer is a data type that is used to access files and perform file I/O operations. A file pointer is essentially a reference to a file, which allows the programmer to read or write data to the file. Here is an overview of how file pointers work in C:
Opening a file: Before a file can be accessed using file I/O functions, it must be opened using the fopen() function, which returns a file pointer that points to the beginning of the file. The fopen() function takes two arguments: the name of the file to open, and the mode in which to open the file (e.g., read, write, append, binary mode).
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "w");
if (fp == NULL) {
printf("Error opening filen");
return -1;
}
fprintf(fp, "This is an example filen");
fclose(fp);
return 0;
}
In this example, the fopen() function is used to open a file named "example.txt" for writing, and the returned file pointer is stored in the fp variable. The if statement checks if the file pointer is NULL, which indicates that the file could not be opened. The fprintf() function is then used to write a string to the file, and the fclose() function is used to close the file.
Reading from a file: Once a file has been opened, data can be read from the file using file I/O functions such as fgets(), fscanf(), or fread(). These functions take a file pointer as their first argument and read data from the file starting from the current position of the file pointer.
#include <stdio.h>
int main() {
char buffer[256];
FILE *fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Error opening filen");
return -1;
}
fgets(buffer, 256, fp);
printf("File contents: %s", buffer);
fclose(fp);
return 0;
}
In this example, the fgets() function is used to read a string of up to 256 characters from the file, starting from the current position of the file pointer. The string is stored in the buffer variable, and the printf() function is used to print the string to the standard output stream.
Writing to a file: Data can be written to a file using file I/O functions such as fprintf(), fwrite(), or fputs(). These functions take a file pointer as their first argument and write data to the file starting from the current position of the file pointer.
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "a");
if (fp == NULL) {
printf("Error opening filen");
return -1;
}
fprintf(fp, "This is a new linen");
fclose(fp);
return 0;
}
In this example, the fprintf() function is used to write a string to the file, starting from the current position of the file pointer. The string is appended to the end of the file because the file was opened in "append" mode using the "a" flag.
In summary, a file pointer is a data type that is used to access files and perform file I/O operations in C programming language. File pointers are returned by the fopen() function, and they can be used to read or write data to the file.