File Pointers in C Language
Introduction
File handling in C is essential for performing various operations on files such as creating, reading, writing, and closing files. A file pointer is a pointer to a structure that contains information about the file, such as its name, status, and current position in the file. This tutorial will cover all the necessary aspects of file pointers in C.
Opening a File
To open a file, you use the fopen function, which returns a file pointer. The syntax for fopen is:
FILE *fopen(const char *filename, const char *mode);
The mode parameter specifies the type of access requested for the file:
- "r": Open for reading.
- "w": Open for writing (truncates file).
- "a": Open for appending.
- "r+": Open for reading and writing.
- "w+": Open for reading and writing (truncates file).
- "a+": Open for reading and appending.
Closing a File
After performing operations on a file, it is a good practice to close the file using the fclose function. The syntax is:
int fclose(FILE *stream);
Reading from a File
You can read data from a file using various functions such as fgetc, fgets, and fread.
FILE *file = fopen("example.txt", "r");
if (file) {
char ch;
while ((ch = fgetc(file)) != EOF)
putchar(ch);
fclose(file);
}
Writing to a File
To write data to a file, you can use functions like fputc, fputs, and fwrite.
FILE *file = fopen("example.txt", "w");
if (file) {
fputs("Hello, World!", file);
fclose(file);
}
File Positioning
File pointers can be moved to a specific position within a file using the fseek function. The syntax is:
int fseek(FILE *stream, long offset, int whence);
The whence parameter can be:
- SEEK_SET: Beginning of the file.
- SEEK_CUR: Current position in the file.
- SEEK_END: End of the file.
Example Program
Here is a complete example demonstrating file pointers in C.
#include <stdio.h>
int main() {
FILE *file;
char ch;
// Open file for writing
file = fopen("example.txt", "w");
if (file) {
fputs("Hello, World!", file);
fclose(file);
}
// Open file for reading
file = fopen("example.txt", "r");
if (file) {
while ((ch = fgetc(file)) != EOF)
putchar(ch);
fclose(file);
}
return 0;
}
Conclusion
File pointers in C are powerful tools for file handling operations. They provide a flexible way to manage files, allowing you to read, write, and reposition file content efficiently. By understanding and utilizing file pointers, you can perform complex file manipulations with ease.