File operations in C involve various tasks related to interacting with files on the system, such as creating, opening, reading from, writing to, and closing files. These operations are facilitated through the use of functions provided by the C Standard Library. Let’s discuss each file operation in detail:
1. File Creation:
- To create a new file, you can use the fopen() function with the “w” mode (write mode). If the file already exists, its contents will be truncated.
FILE *file; file = fopen(“example.txt”, “w”); // Create a new file named “example.txt”
2. Opening Files:
- To open an existing file, you use the fopen() function with appropriate mode (“r” for read, “w” for write, “a” for append, etc.).
FILE *file; file = fopen(“example.txt”, “r”); // Open an existing file named “example.txt” for reading
3. Reading from Files:
- File reading operations involve reading data from a file and storing it in variables or arrays in memory.
- Common functions for reading from files include fscanf() (for formatted input) and fgets() (for reading lines of text).
char buffer[100]; fgets(buffer, sizeof(buffer), file); // Read a line from the file
4. Writing to Files:
- File writing operations involve writing data from variables or arrays in memory to a file.
- Common functions for writing to files include fprintf() (for formatted output) and fputs() (for writing strings).
fprintf(file, “%s %d\n”, “Value:”, 10); // Write formatted output to the file
5. Closing Files:
- After completing operations on a file, it should be closed using the fclose() function to release the resources associated with it.
fclose(file); // Close the file
6. Error Handling:
- Error handling is crucial when performing file operations to handle situations such as file not found, insufficient permissions, or disk full errors.
- Functions like feof() and ferror() are used to check for end-of-file and error conditions during file operations.
if (file == NULL)
{
perror(“Error opening file”);
return 1;
}
7. File Positioning:
- File positioning functions like fseek() and ftell() are used to move the file pointer to a specific position within the file and determine the current position, respectively.
fseek(file, 0, SEEK_END); // Move the file pointer to the end of the file
long fileSize = ftell(file); // Get the current position of the file pointer (end of file)
8. Binary vs. Text Files:
- Files can be classified into binary and text files based on the format of data they contain.
- Different file handling functions are used for text and binary file operations.
FILE *binaryFile;
binaryFile = fopen(“example.bin”, “rb”); // Open a binary file named “example.bin” for reading in binary mode
Understanding file operations in C enables you to work with files efficiently, perform tasks such as data input/output, and handle file-related errors effectively. Proper error handling is crucial to ensure robustness and reliability in file operations.