Operations on Files in C
Working with files in C involves several important operations that allow you to open, read, write, append, and close files. These operations help manage data storage, making it possible to interact with files for persistent data handling. At SamagraCS Educational Technology, we break down the key file operations and provide examples to help you master these concepts.
Key Operations on Files in C
Here are the main operations you can perform on files in C:
- Opening a File: Using
fopen()
to open a file. - Reading from a File: Using
fscanf()
,fgets()
,fread()
. - Writing to a File: Using
fprintf()
,fputs()
,fwrite()
. - Appending to a File: Using
fopen()
in append mode ("a"
,"a+"
). - Closing a File: Using
fclose()
. - File Positioning: Using
fseek()
,ftell()
, andrewind()
to manage file pointers. - Error Handling: Using functions like
feof()
andferror()
to detect errors and end-of-file conditions.
1. Opening a File (fopen()
)
Before performing any operations on a file, you must open the file using the fopen()
function. This function returns a file pointer, which you’ll use in subsequent operations like reading or writing.
Syntax:
FILE *fopen(const char *filename, const char *mode);
- filename: The name of the file you want to open.
- mode: The mode in which you want to open the file (e.g.,
"r"
,"w"
,"a"
,"rb"
,"wb"
).
Example:
FILE *filePointer;
filePointer = fopen("data.txt", "r"); // Open file for reading
if (filePointer == NULL) {
printf("Error opening file!\n");
}
2. Reading from a File
Once a file is open, you can read data from it using functions like fscanf()
, fgets()
, and fread()
.
a) fscanf()
– Reading Formatted Data
FILE *filePointer;
char name[50];
int age;
filePointer = fopen("data.txt", "r");
if (filePointer != NULL) {
fscanf(filePointer, "Name: %s\n", name);
fscanf(filePointer, "Age: %d\n", &age);
printf("Name: %s, Age: %d\n", name, age);
fclose(filePointer);
}
b) fgets()
– Reading a String from a File
FILE *filePointer;
char buffer[100];
filePointer = fopen("data.txt", "r");
if (filePointer != NULL) {
fgets(buffer, 100, filePointer);
printf("Read from file: %s", buffer);
fclose(filePointer);
}
c) fread()
– Reading Binary Data
FILE *filePointer;
int numbers[5];
filePointer = fopen("numbers.bin", "rb");
if (filePointer != NULL) {
fread(numbers, sizeof(int), 5, filePointer);
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
fclose(filePointer);
}
3. Writing to a File
You can write data to a file using fprintf()
, fputs()
, or fwrite()
.
a) fprintf()
– Writing Formatted Data
FILE *filePointer;
filePointer = fopen("output.txt", "w");
if (filePointer != NULL) {
fprintf(filePointer, "Name: Pawan Jaiswal\n");
fprintf(filePointer, "Age: 21\n");
fclose(filePointer);
}
b) fputs()
– Writing Strings
FILE *filePointer;
filePointer = fopen("output.txt", "w");
if (filePointer != NULL) {
fputs("SamagraCS Educational Technology\n", filePointer);
fclose(filePointer);
}
c) fwrite()
– Writing Binary Data
FILE *filePointer;
int numbers[] = {1, 2, 3, 4, 5};
filePointer = fopen("binarydata.bin", "wb");
if (filePointer != NULL) {
fwrite(numbers, sizeof(int), 5, filePointer);
fclose(filePointer);
}
4. Appending to a File
To add data to the end of an existing file without overwriting its contents, you can open the file in append mode using "a"
or "a+"
.
Example:
FILE *filePointer;
filePointer = fopen("data.txt", "a");
if (filePointer != NULL) {
fprintf(filePointer, "Added new line.\n");
fclose(filePointer);
}
In this case, the new line "Added new line."
is added to the end of data.txt
.
5. Closing a File (fclose()
)
After finishing any file operation, always close the file using fclose()
to free up system resources and ensure all data is written properly.
Syntax:
int fclose(FILE *filePointer);
Example:
fclose(filePointer); // Closes the file
6. File Positioning Functions
C provides functions to manage the position of the file pointer, which helps when navigating within the file.
a) fseek()
– Move File Pointer
The fseek()
function moves the file pointer to a specific position in the file.
int fseek(FILE *filePointer, long offset, int origin);
- offset: Number of bytes to move.
- origin: Position to move from (
SEEK_SET
,SEEK_CUR
,SEEK_END
).
Example:
FILE *filePointer;
filePointer = fopen("data.txt", "r");
fseek(filePointer, 10, SEEK_SET); // Move pointer to byte 10
b) ftell()
– Get File Pointer Position
The ftell()
function returns the current position of the file pointer.
long ftell(FILE *filePointer);
Example:
long position = ftell(filePointer); // Get current position
printf("File pointer is at byte: %ld\n", position);
c) rewind()
– Reset File Pointer
The rewind()
function sets the file pointer to the beginning of the file.
void rewind(FILE *filePointer);
Example:
rewind(filePointer); // Move the file pointer to the beginning
7. Error Handling in File I/O
C provides functions like feof()
and ferror()
to detect the end of the file or any errors during file operations.
a) feof()
– Check End of File
The feof()
function returns non-zero if the file pointer has reached the end of the file.
int feof(FILE *filePointer);
Example:
if (feof(filePointer)) {
printf("End of file reached.\n");
}
b) ferror()
– Check for Errors
The ferror()
function checks if any error occurred during file operations.
int ferror(FILE *filePointer);
Example:
if (ferror(filePointer)) {
printf("An error occurred while reading the file.\n");
}
Mastering file operations in C is essential for managing data storage and retrieval in applications. By understanding the key operations—opening, reading, writing, appending, closing, file positioning, and error handling—you’ll be able to efficiently handle files in C programming.
At SamagraCS Educational Technology, we encourage you to practice these operations with different file types and scenarios. If you have any questions, feel free to reach out to Pawan & Pooja, or the team. Happy coding!