Introduction to File I/O
File input/output (I/O) operations are a crucial part of many programs, allowing them to read from and write to files on disk. This capability enables data persistence, where the data created or modified during program execution can be stored for future use. In C, file I/O operations are handled through a set of standard library functions provided by the <stdio.h> header.
File Handling in C
File handling in C involves four main steps:
- Opening a file
- Performing read/write operations
- Closing the file
- Handling file errors
Opening a File
To open a file, you use the fopen() function, which returns a pointer to a FILE object. This pointer is used to identify the file in subsequent operations.
Syntax
FILE *fopen(const char *filename, const char *mode);
filename: The name of the file to open.mode: The mode in which to open the file.
File Modes
"r": Opens a file for reading. The file must exist."w": Opens a file for writing. Creates a new file or truncates an existing file."a": Opens a file for appending. Data is added to the end of the file."r+": Opens a file for reading and writing. The file must exist."w+": Opens a file for reading and writing. Creates a new file or truncates an existing file."a+": Opens a file for reading and appending. Creates a new file if it does not exist.
Example
#include <stdio.h>
int main() {
FILE *file;
// Open a file for writing
file = fopen("example.txt", "w");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Perform file operations here
// Close the file
fclose(file);
return 0;
}
Writing to a File
To write data to a file, you can use functions such as fprintf(), fputs(), and fwrite().
fprintf()
The fprintf() function is similar to printf(), but it writes formatted output to a file instead of the standard output.
Syntax
int fprintf(FILE *stream, const char *format, ...);
stream: Pointer to theFILEobject.format: Format string....: Additional arguments for the format string.
Example
#include <stdio.h>
int main() {
FILE *file;
// Open a file for writing
file = fopen("example.txt", "w");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write formatted data to the file
fprintf(file, "Hello, World!\n");
fprintf(file, "This is a number: %d\n", 42);
// Close the file
fclose(file);
return 0;
}
fputs()
The fputs() function writes a string to a file.
Syntax
int fputs(const char *str, FILE *stream);
str: Pointer to the string to write.stream: Pointer to theFILEobject.
Example
#include <stdio.h>
int main() {
FILE *file;
// Open a file for writing
file = fopen("example.txt", "w");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write a string to the file
fputs("Hello, World!\n", file);
fputs("This is a simple string.\n", file);
// Close the file
fclose(file);
return 0;
}
fwrite()
The fwrite() function writes a block of data to a file.
Syntax
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
ptr: Pointer to the data to write.size: Size of each element to write.count: Number of elements to write.stream: Pointer to theFILEobject.
Example
#include <stdio.h>
int main() {
FILE *file;
int numbers[] = {1, 2, 3, 4, 5};
// Open a file for writing
file = fopen("numbers.bin", "wb");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write the array to the file
fwrite(numbers, sizeof(int), 5, file);
// Close the file
fclose(file);
return 0;
}
Reading from a File
To read data from a file, you can use functions such as fscanf(), fgets(), and fread().
fscanf()
The fscanf() function is similar to scanf(), but it reads formatted input from a file.
Syntax
int fscanf(FILE *stream, const char *format, ...);
stream: Pointer to theFILEobject.format: Format string....: Additional arguments for the format string.
Example
#include <stdio.h>
int main() {
FILE *file;
char str[100];
int num;
// Open a file for reading
file = fopen("example.txt", "r");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read formatted data from the file
fscanf(file, "%s", str);
fscanf(file, "%d", &num);
// Print the data
printf("Read string: %s\n", str);
printf("Read number: %d\n", num);
// Close the file
fclose(file);
return 0;
}
fgets()
The fgets() function reads a string from a file.
Syntax
char *fgets(char *str, int n, FILE *stream);
str: Pointer to the buffer to store the string.n: Maximum number of characters to read.stream: Pointer to theFILEobject.
Example
#include <stdio.h>
int main() {
FILE *file;
char str[100];
// Open a file for reading
file = fopen("example.txt", "r");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read a string from the file
fgets(str, 100, file);
// Print the string
printf("Read string: %s\n", str);
// Close the file
fclose(file);
return 0;
}
fread()
The fread() function reads a block of data from a file.
Syntax
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
ptr: Pointer to the buffer to store the data.size: Size of each element to read.count: Number of elements to read.stream: Pointer to theFILEobject.
Example
#include <stdio.h>
int main() {
FILE *file;
int numbers[5];
// Open a file for reading
file = fopen("numbers.bin", "rb");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read the array from the file
fread(numbers, sizeof(int), 5, file);
// Print the numbers
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
// Close the file
fclose(file);
return 0;
}
Closing a File
To close a file, you use the fclose() function, which ensures that any buffered data is flushed to the file and releases the file descriptor.
Syntax
int fclose(FILE *stream);
stream: Pointer to theFILEobject.
Example
#include <stdio.h>
int main() {
FILE *file;
// Open a file for writing
file = fopen("example.txt", "w");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Perform file operations here
// Close the file
fclose(file);
return 0;
}
Error Handling
To handle file errors, you can use functions such as ferror() and perror().
ferror()
The ferror() function checks if an error occurred during a previous file operation.
Syntax
int ferror(FILE *stream);
stream: Pointer to theFILEobject.- Returns: Non-zero if an error occurred, zero otherwise.
Example
#include <stdio.h>
int main() {
FILE *file;
// Open a file for reading
file = fopen("example.txt", "r");
// Check if the file was opened successfully
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Perform file operations here
// Check for errors
if (ferror(file)) {
printf("An error occurred while reading the file.\n");
}
// Close the file
fclose(file);
return 0;
}
perror()
The perror() function prints a descriptive error message to the standard error stream.
Syntax
void perror(const char *str);
str: Pointer to the string to prefix the error message.
Example
#include <stdio.h>
int main() {
FILE *file;
// Open a file for reading
file = fopen("example.txt", "r");
// Check if the file was opened successfully
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Perform file operations here
// Close the file
fclose(file);
return 0;
}
Conclusion
File I/O operations in C provide a powerful way to read from and write to files, enabling data persistence and manipulation of large data sets. By understanding how to use functions such as fopen(), fprintf(), fputs(), fwrite(), fscanf(), fgets(), fread(), fclose(), and handling errors with ferror() and perror(), you can efficiently manage file operations in your programs. Mastery of these techniques will allow you to create robust applications that can handle complex data storage and retrieval requirements.

Leave a Reply