File Pointers
A file pointer in the Windows API, represented by a FILE* handle in the C Runtime Library, tracks the current read/write position within an open file stream. It is central to sequential and random access operations.
Key Functions
fopen– Open a file and obtain a file pointer.fclose– Close a file pointer and release resources.fseek– Move the file pointer to a specific location.ftell– Retrieve the current offset of the file pointer.rewind– Reset the file pointer to the beginning of the file.feof– Test for end‑of‑file condition.ferror– Detect I/O errors on the stream.
Using File Pointers – Example
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp = fopen("example.txt", "w+");
if (!fp) {
perror("fopen");
return EXIT_FAILURE;
}
// Write data
fputs("Hello, world!\n", fp);
fputs("File pointers are useful.\n", fp);
// Move to the beginning
rewind(fp);
// Read and display
char buffer[64];
while (fgets(buffer, sizeof(buffer), fp)) {
puts(buffer);
}
// Seek to the second line (offset after first line)
fseek(fp, 14, SEEK_SET); // 14 bytes offset
fputs("INSERTED LINE\n", fp);
// Clean up
fclose(fp);
return EXIT_SUCCESS;
}
Best Practices
- Always check the return value of
fopenbefore using the pointer. - Use
fcloseto prevent resource leaks. - Validate the result of
fseekandftellfor error handling. - Prefer binary mode (
"rb","wb") when dealing with non‑text data. - When performing random access, calculate offsets based on
sizeofyour data structures.