File Handling in C
File handling in C is an essential skill that enables programmers to create, read, write, and manage files. Files are used for storing data permanently, making it accessible even after the program has terminated. Here's an introduction to file handling concepts in C.
Persistence : Data stored in files remains available even after the program ends.
Large Data Management : Files can store large amounts of data, exceeding the memory limitations of a program.
Data Sharing : Files facilitate data sharing between programs or different executions of the same program.
Text Files : Contain data in a readable format (ASCII characters). Examples include .txt, .csv, etc.
Binary Files : Contain data in binary format, which is not human-readable. Examples include executables, images, and compiled programs.
When opening a file, specify the mode to determine the operation type :
- "r" : Open for reading (file must exist).
- "w" : Open for writing (creates a new file or truncates an existing file).
- "a" : Open for appending (data is written at the end of the file).
- "r+" : Open for reading and writing (file must exist).
- "w+" : Open for reading and writing (creates a new file or truncates an existing file).
- "a+" : Open for reading and appending (data is written at the end of the file).
Use the fopen function to open a file. It returns a pointer to a FILE object.
FILE *fopen(const char *filename, const char *mode);
- filename is the name of the file to open.
- mode is the mode in which to open the file.
Example :
Use the fclose function to close an opened file.
int fclose(FILE *stream);
Example :
Use functions like fputc, fputs, and fwrite to write data to a file -
- fputc : Writes a single character.
- fputs : Writes a string.
- fwrite : Writes binary data.
int fputc(int char, FILE *stream);
int fputs(const char *str, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
Example :
Use functions like fgetc, fgets, and fread to read data from a file.
- fgetc : Reads a single character.
- fgets : Reads a string.
- fread : Reads binary data.
int fgetc(FILE *stream);
char *fgets(char *str, int n, FILE *stream);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
Always check the return values of file operations to handle errors appropriately. Use perror or strerror to get descriptive error messages.
File handling in C is a fundamental concept that allows programs to interact with data storage efficiently. By mastering file operations, programmers can build applications that manage data effectively, ensuring data persistence and accessibility.