Working with Files in C Programming
In C, file operations are managed using a pointer variable that references a file, known as a file pointer. This is analogous to file objects in other languages like Java.
File Pointer Declaration
FILE *filePointer;
Opening Files with fopen
The fopen function is used to open a file. Its syntax is:
filePointer = fopen("filename", "mode");
filePointer: A variable declared asFILE *.filename: A string specifying the file name.mode: A string indicating the file access type.
Closing Files with fclose
After file operations, close the file with fclose to prevent data loss:
fclose(filePointer);
- Returns 0 on success; non-zero indicates an error.
Example Workflow
- Include the standard I/O header:
#include <stdio.h>
- Declare a file pointer:
FILE *fp = NULL;
- Open a file:
fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
exit(1);
}
- Perform file operations.
- Close the file:
fclose(fp);
File Access Modes
r: Read from an existing file.w: Write to a new file; overwrites if exists.a: Append to an existing file; creates if not exists.r+: Read and write to an existing file.w+: Read and write to a new file; overwrites if exists.a+: Append and read from a file; creates if not exists.t: Text file (default).b: Binary file.
Key Points
- Modes combine characters:
r,w,a,t,b,+. - Use
ronly for existing files. wcreates or overwrites files.aappends data; creates files if needed.- Check
fopenreturn forNULLto handle errors. - Text files involve ASCII-binary conversion; binary files do not.
- Standard streams (e.g., stdin, stdout) are pre-opened.
Character I/O Functions
fgetc: Reads a single character; returnsEOFat end.fputc: Writes a single character.
String I/O Functions
fgets: Reads a string up to a specified length or newline/EOF.
fgets(buffer, size, fp);
fputs: Writes a string; returns number of characters written.
Block I/O Functions
fread: Reads blocks of data.
fread(dataBuffer, elementSize, count, fp);
fwrite: Writes blocks of data.
fwrite(dataBuffer, elementSize, count, fp);
Formatted I/O Functions
fprintf: Writes formatted data to a file.
fprintf(fp, "%d %s", num, str);
fscanf: Reads formatted data from a file.
fscanf(fp, "%d %s", &num, str);
Random File Access
Use rewind or fseek to move the file position pointer.
rewind(fp): Resets pointer to file start.fseek(fp, offset, origin): Moves pointer relative toorigin(0=start, 1=current, 2=end).
fseek(fp, 50L, SEEK_SET);
- Best used with binary files due to text file conversion issues.
File Status Functiosn
feof(fp): Returns non-zero if end-of-file is reached.ferror(fp): Checks for errors during file operations.clearerr(fp): Clears error and end-of-file flags.