Optimizing File Input/Output in C Programming
In the realm of C programming, efficient file input/output operations are crucial. This blog explores essential functions and practices for handling file data, ensuring clarity and precision throughout the process.
Formatted Disk I/O Function:
To diversify file writing formats, we leverage fprintf() and fscanf() functions. These are akin to printf and scanf but specifically tailored for file operations.
fprintf(fp, "format specifier", variable_list);
Here, fp denotes the file pointer associated with the target file. The format specifier defines the data format, and the variable list encompasses variables and constants of various data types.
fscanf(fp, "format specifier", variable list);
Similarly, when reading from a file, fscanf() requires the file pointer, format specifier, and a variable list.
Reading And Writing Data In Binary Mode:
Files conventionally handle data in character form. For instance, storing the integer value '3421' requires 4 bytes, compared to its original 2-byte memory footprint. To overcome this, binary mode ('b') ensures data is processed in its original format. Consider these functions for reading and writing in binary:
fread(&variable, sizeof(variable), 1, filepointer);
Example:
struct Emp e;
fread(&e, sizeof(e), 1, fp);
fwrite(&variable, sizeof(variable), 1, filepointer);
Example:
struct Emp e;
fwrite(&e, sizeof(e), 1, fp);
Random File Access:
For scenarios requiring random data access, C provides fseek, ftell, and rewind.
ftell:
n = ftell(p);
This function returns a long integer representing the current position in the file.rewind
rewind(fp);
This resets the file position to the start.fseek:
fseek(filepointer, offset, position);
Here, filepointer is the file's pointer, offset is a long integer, and position denotes the reference point.
Program 1: File Copying
#include <stdio.h>
void main() {
FILE *fp, *fp1;
char ch;
char sfile[15], tfile[15];
printf("\nEnter source file name:");
scanf("%s", sfile);
fp = fopen(sfile, "r");
if (fp == NULL) {
printf("\nFile does not exist");
}
printf("\nEnter Target File:");
scanf("%s", tfile);
fp1 = fopen(tfile, "w");
if (fp1 == NULL) {
printf("Unable to open file");
}
while (1) {
ch = fgetc(fp);
if (ch == EOF)
break;
fputc(ch, fp1);
}
fclose(fp);
fclose(fp1);
printf("File Copied");
}
This program exemplifies copying content from one file to another. Correcting syntax errors and enhancing readability makes this a practical example for learners.
Conclusion:
Mastering file I/O in C involves understanding these functions and techniques. Whether handling formatted data, working in binary mode, or navigating files randomly, these insights empower programmers to optimize their file operations.