File Operations in C
Introduction
File operations are an essential part of any programming language. In C, file handling is done using a set of standard library functions. This tutorial will walk you through the fundamental operations you can perform on files in C, such as opening, reading, writing, and closing files.
Opening a File
To perform any operation on a file, it must first be opened. The fopen function is used to open a file in C. This function returns a pointer to a FILE object that can be used to perform subsequent operations on the file.
Example:
FILE *filePointer; filePointer = fopen("example.txt", "r"); if (filePointer == NULL) { printf("Error opening file.\n"); return 1; }
The fopen function takes two arguments: the name of the file and the mode in which the file should be opened. Common modes include:
- "r" - Read mode
- "w" - Write mode
- "a" - Append mode
Reading from a File
Once a file is opened in read mode, you can read its contents using the fscanf or fgets functions.
Example: Reading a single line from a file using fgets
FILE *filePointer; char buffer[100]; filePointer = fopen("example.txt", "r"); if (filePointer == NULL) { printf("Error opening file.\n"); return 1; } if (fgets(buffer, 100, filePointer) != NULL) { printf("Read: %s", buffer); } fclose(filePointer);
The fgets function reads up to n-1 characters from the file and stores them in the buffer. It stops reading after reaching a newline or the end of the file.
Writing to a File
To write data to a file, you can use the fprintf or fputs functions.
Example: Writing a string to a file using fputs
FILE *filePointer; filePointer = fopen("example.txt", "w"); if (filePointer == NULL) { printf("Error opening file.\n"); return 1; } fputs("Hello, World!\n", filePointer); fclose(filePointer);
The fputs function writes a string to the file. The fprintf function can be used to write formatted data to the file.
Closing a File
After you are done with file operations, it is important to close the file using the fclose function to free up resources.
Example:
FILE *filePointer; filePointer = fopen("example.txt", "r"); // Perform file operations fclose(filePointer);
The fclose function takes a file pointer as its argument and closes the file associated with it.
Conclusion
In this tutorial, we covered the basics of file operations in C, including opening, reading, writing, and closing files. These fundamental operations form the basis of more advanced file handling techniques, which can be explored as you become more comfortable with basic file operations.