In C programming, files are used to store data permanently, either for input or output. C provides a set of functions for working with files, allowing you to read from and write to them. These files can be of two types:
Working with files is a crucial aspect of C programming, particularly when you need to store large amounts of data or retrieve data for later use. C offers functions that allow you to open, read, write, and close files.
To work with files in C, you use the standard library provided by C, particularly <stdio.h>, which includes functions for opening, reading, writing, and closing files.
fopen()The fopen() function is used to open a file. It takes two parameters:
Syntax:
FILE *fopen(const char *filename, const char *mode);
Modes:
"r": Opens the file for reading. If the file does not exist, the operation fails."w": Opens the file for writing. If the file exists, it is overwritten. If it does not exist, a new file is created."a": Opens the file for appending. Data is added at the end of the file."r+": Opens the file for both reading and writing. The file must exist."w+": Opens the file for both reading and writing. The file is created or overwritten."a+": Opens the file for both reading and appending.Example:
FILE *file = fopen("example.txt", "w"); // Open "example.txt" for writing
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
If fopen() fails to open the file (for example, due to insufficient permissions or an incorrect path), it returns NULL.
fclose()Once you're done working with a file, you should always close it using fclose(). This releases any resources allocated for the file.
Syntax:
int fclose(FILE *stream);
Example:
fclose(file); // Close the file after use
There are several functions to read from a file, depending on the type of data you want to read.
fgetc() – Read a Single CharacterSyntax:
int fgetc(FILE *stream);
Example:
char c;
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
c = fgetc(file); // Read a single character
printf("%c\n", c); // Print the character
fclose(file);
fgetc() returns the next character from the file. If it reaches the end of the file, it returns EOF (end-of-file).
fgets() – Read a String (Line)char *fgets(char *str, int n, FILE *stream);
fgets() reads a line from the file into a string. The second parameter (n) specifies the maximum number of characters to read.
char buffer[100];
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
fgets(buffer, sizeof(buffer), file); // Read a line into buffer
printf("Line: %s", buffer); // Print the line
fclose(file);
fread() – Read Binary Datafread() is used to read binary data from a file.
Syntax:
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
Example:
FILE *file = fopen("binary.dat", "rb");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
int arr[5];
fread(arr, sizeof(int), 5, file); // Read 5 integers from the file
fclose(file);
Just like reading, there are different functions for writing to a file based on the type of data you wish to write.
fputc() – Write a Single CharacterSyntax:
int fputc(int char, FILE *stream);
Example:
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
fputc('A', file); // Write a single character to the file
fclose(file);
fputs() – Write a StringSyntax:
int fputs(const char *str, FILE *stream);
Example:
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
fputs("Hello, World!", file); // Write a string to the file
fclose(file);
fwrite() – Write Binary Datafwrite() is used to write binary data to a file.
Syntax:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
Example:
FILE *file = fopen("binary.dat", "wb");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
int arr[5] = {1, 2, 3, 4, 5};
fwrite(arr, sizeof(int), 5, file); // Write 5 integers to the file
fclose(file);
You can move the file pointer to a specific position in a file using these functions.
fseek() – Move the File Pointerint fseek(FILE *stream, long offset, int whence);
fseek() moves the file pointer to a specific location. The whence parameter can be:
SEEK_SET: Set the position to offset from the beginning.
SEEK_CUR: Set the position to offset from the current position.
SEEK_END: Set the position to offset from the end of the file.
Example:
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
fseek(file, 10, SEEK_SET); // Move the pointer 10 bytes from the beginning
fclose(file);
ftell() – Get the Current Positionftell() returns the current position of the file pointer.
Syntax:
long ftell(FILE *stream);
Example:
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
fseek(file, 10, SEEK_SET); // Move the pointer
long pos = ftell(file); // Get the current position
printf("Current position: %ld\n", pos);
fclose(file);
C provides a set of functions for detecting file errors.
feof() – Check for End of Filefeof() checks whether the end of the file has been reached.
Syntax:
int feof(FILE *stream);
Example:
FILE *file = fopen("example.txt", "r");
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch); // Print characters until end of file
}
fclose(file);
ferror() – Check for File Errorsferror() checks for errors during reading or writing operations.
Syntax:
int ferror(FILE *stream);
**Example
Open this section to load past papers