File Classification
1. Program Files
Files with extansions: .c (source file), .obj (object file), .exe (executable)
2. Data Files
Files that store data, such as: .txt, .jpg, .log, etc.
File Usage
File Pointer
The file pointer references the file information block. The pointer type is FILE*. Each time a file is opened, the pointer starts at the beginning of the file.
FILE* fileHandle; // Create a file pointer
File Opening and Closing
fileHandle = fopen("data.txt", "w"); // Open data.txt in write mode
fclose(fileHandle); // Close the file
File Open Modes
| Mode | Permission | Behavior | If File Does Not Exist |
|---|---|---|---|
| "r" | Read only | Read data from file | Returns NULL |
| "w" | Write only | Write data to file | Creates new file |
| "a" | Append | Add data to end of file | Creates new file |
| "rb" | Read only | Read data in binary mode | Returns NULL |
| "wb" | Write only | Write data in binary mode | Creates new file |
| "ab" | Append | Append data in binary mode | Creates new file |
| "r+" | Read/Write | Read or write data | Returns NULL |
| "w+" | Read/Write | Read or write data | Creates new file |
| "a+" | Read/Write | Read or append data | Creates new file |
| "rb+" | Read/Write | Read/write in binary mode | Returns NULL |
| "wb+" | Read/Write | Read/write in binary mode | Creates new file |
| "ab+" | Read/Write | Read/apend in binary mode | Creates new file |
File Operation Functions
| Function | Purpose | Applicable To |
|---|---|---|
| fgetc() | Read a single character from file | All input streams |
| fputc() | Write a single character to file | All output streams |
| fgets() | Read a string from file | All input streams |
| fputs() | Write a string to file | All output streams |
| fscanf() | Read formatted data from file | All input streams |
| fprintf() | Write formatted data to file | All output streams |
| fread() | Read binary data from file | Files |
| fwrite() | Write binary data to file | Files |
Character I/O Functions
fgetc
int fgetc(FILE* stream);
Reads one character at the current file position indicated by stream. The file position indicator advances by one character.
Returns the character read on success. Returns EOF (-1) on reaching end-of-file or on read error.
Example:
FILE* fileHandle;
fileHandle = fopen("data.txt", "r");
if (fileHandle != NULL) {
int ch;
while ((ch = fgetc(fileHandle)) != EOF) {
printf("%c ", ch);
}
fclose(fileHandle);
fileHandle = NULL;
}
fputc
int fputc(int character, FILE* stream);
Writes character to the file pointed to by stream. The file position indicator advances by one character.
Returns the character written on success. Returns EOF on failure.
Note: Each time a file is opened, the position indicator starts at the beginning, meaning new data overwrites existing data.
Example:
FILE* fileHandle;
fileHandle = fopen("data.txt", "w");
if (fileHandle != NULL) {
for (int i = 'A'; i <= 'Z'; i++) {
fputc(i, fileHandle);
}
fclose(fileHandle);
fileHandle = NULL;
}
String I/O Functions
fgets
char* fgets(char* str, int num, FILE* stream);
Reads up to num-1 characters from stream and stores them in str. The function automatically appends a \0 at the end. If a newline character \n is encountered, reading stops after the newline (which is included in the string).
Returns str on success. Returns NULL on failure or when end-of-file is reached.
Example:
FILE* fileHandle;
char buffer[128] = "xxxxxxxxxxxxxxx";
fileHandle = fopen("data.txt", "r");
if (fileHandle != NULL) {
fgets(buffer, 10, fileHandle);
puts(buffer);
fclose(fileHandle);
fileHandle = NULL;
}
fputs
int fputs(const char* str, FILE* stream);
Writes the string pointed to by str to the file pointed to by stream. The terminating null character is not written.
Returns a non-negative value on success. Returns EOF on failure.
Example:
FILE* fileHandle;
const char* message = "Hello, World!";
fileHandle = fopen("data.txt", "w");
if (fileHandle != NULL) {
fputs(message, fileHandle);
fclose(fileHandle);
fileHandle = NULL;
}
Formatted I/O Functions
fscanf
int fscanf(FILE* stream, const char* format, ...);
Similar to scanf, but reads from a file instead of standard input. Reading stops when whitespace is encountered.
Returns the number of items successfully read and assigned. Returns EOF on failure.
Example:
FILE* fileHandle;
char name[30];
int age;
double salary;
fileHandle = fopen("data.txt", "r");
if (fileHandle != NULL) {
int count;
while ((count = fscanf(fileHandle, "%s %d %lf", name, &age, &salary)) != EOF) {
if (count == 3) {
printf("Name: %s, Age: %d, Salary: %.2f\n", name, age, salary);
}
}
fclose(fileHandle);
fileHandle = NULL;
}
fprintf
int fprintf(FILE* stream, const char* format, ...);
Similar to printf, but writes to a file instead of the screen.
Returns the total number of characters written. Returns a negative value on failure.
Example:
FILE* fileHandle;
const char* title = "Employee Record";
int id = 1001;
double score = 95.5;
fileHandle = fopen("data.txt", "w");
if (fileHandle != NULL) {
fprintf(fileHandle, "%s %d %.1f", title, id, score);
fclose(fileHandle);
fileHandle = NULL;
}
Binary I/O Functions
fread
size_t fread(void* ptr, size_t size, size_t count, FILE* stream);
Reads count elements of size bytes each from stream into the memory area pointed to by ptr.
Returns the number of elements successfully read. If this number differs from count, either an error occurred or end-of-file was reached. Returns 0 if size or count is 0.
Example:
FILE* fileHandle;
unsigned char data[50] = {0};
fileHandle = fopen("data.bin", "rb");
if (fileHandle != NULL) {
size_t items = fread(data, 1, 20, fileHandle);
if (items > 0) {
printf("Read %zu bytes\n", items);
}
fclose(fileHandle);
fileHandle = NULL;
}
fwrite
size_t fwrite(const void* ptr, size_t size, size_t count, FILE* stream);
Writes count elements of size bytes each from ptr to stream in binary form.
Returns the number of elements successfully written. Returns 0 if size or count is 0.
Example:
FILE* fileHandle;
const char* content = "Binary Data Block";
fileHandle = fopen("data.bin", "wb");
if (fileHandle != NULL) {
size_t items = fwrite(content, 1, 10, fileHandle);
printf("Wrote %zu elements\n", items);
fclose(fileHandle);
fileHandle = NULL;
}
Status Detection Functions
feof
int feof(FILE* stream);
Tests whether the end-of-file indicator is set for stream.
Returns non-zero if end-of-file was reached. Returns 0 otherwise.
ferror
int ferror(FILE* stream);
Tests whether the error indicator is set for stream.
Returns non-zero if an error occurred. Returns 0 otherwise.
Example:
FILE* fileHandle;
unsigned char buffer[32] = {0};
fileHandle = fopen("data.txt", "r");
if (fileHandle != NULL) {
while (fread(buffer, 1, 1, fileHandle) == 1);
if (feof(fileHandle)) {
printf("Reached end of file\n");
} else if (ferror(fileHandle)) {
printf("Read error occurred\n");
}
fclose(fileHandle);
fileHandle = NULL;
}
Random Access Operations
fseek
int fseek(FILE* stream, long int offset, int origin);
Sets the file position indicator for stream to the location specified by origin plus offset.
The origin parameter can be:
SEEK_SET- Beginning of fileSEEK_CUR- Current positionSEEK_END- End of file
Returns 0 on success. Returns non-zero on failure.
Example:
FILE* fileHandle;
fileHandle = fopen("data.txt", "r");
if (fileHandle != NULL) {
// Position: SEEK_END = end, offset = -2 means 2 bytes before end
fseek(fileHandle, -2, SEEK_END);
char ch = fgetc(fileHandle);
putchar(ch); // For file content "ABCDE", outputs "D"
fclose(fileHandle);
fileHandle = NULL;
}
ftell
long int ftell(FILE* stream);
Returns the current file position indicator for stream.
Returns the offset from the beginning of the file. Returns -1 on error.
Example:
FILE* fileHandle;
fileHandle = fopen("data.txt", "r");
if (fileHandle != NULL) {
fseek(fileHandle, -3, SEEK_END);
long pos = ftell(fileHandle);
printf("Position: %ld\n", pos);
fclose(fileHandle);
fileHandle = NULL;
}
rewind
void rewind(FILE* stream);
Sets the file position indicator for stream to the beginning of the file.
Example:
FILE* fileHandle;
fileHandle = fopen("data.txt", "r");
if (fileHandle != NULL) {
// Move to 5 bytes before end
fseek(fileHandle, -5, SEEK_END);
// Return to beginning
rewind(fileHandle);
long pos = ftell(fileHandle); // Will be 0
printf("Position after rewind: %ld\n", pos);
fclose(fileHandle);
fileHandle = NULL;
}