In C, file operations allow you to perform different tasks such as opening a file, reading from it, writing to it, and closing it. Let's dive into the essential file operations in C and see how to use them effectively.
fopen()
— Open a filefwrite()
— Write to a filefread()
— Read from a filefclose()
— Close a file
fopen()
— Opening FilesThe fopen()
function is used to open a file. The file can be opened in different modes such as read, write, append, etc. Here's how to open a file:
FILE *fopen(const char *filename, const char *mode);
The mode
argument specifies how the file should be accessed. Here are some common modes:
fopen()
#includeint main() { FILE *file = fopen("sample.txt", "w"); // Open file for writing if (file == NULL) { printf("Error opening file.\n"); return 1; } fprintf(file, "This is a test.\n"); // Write to file fclose(file); // Close file return 0; }
fwrite()
— Writing to a FileThe fwrite()
function is used to write data to a file in binary format. It's commonly used for writing structures or arrays to files.
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
fwrite()
#includeint main() { FILE *file = fopen("numbers.dat", "wb"); // Open file for writing binary data if (file == NULL) { printf("Error opening file.\n"); return 1; } int numbers[] = {1, 2, 3, 4, 5}; fwrite(numbers, sizeof(int), 5, file); // Write an array to the file fclose(file); // Close the file return 0; }
numbers
is written to the file "numbers.dat" in binary format using fwrite()
.
fread()
— Reading from a FileThe fread()
function reads binary data from a file and stores it into a buffer. Here's the syntax:
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
fread()
#includeint main() { FILE *file = fopen("numbers.dat", "rb"); // Open file for reading binary data if (file == NULL) { printf("Error opening file.\n"); return 1; } int numbers[5]; fread(numbers, sizeof(int), 5, file); // Read data from the file fclose(file); // Close the file for(int i = 0; i < 5; i++) { printf("%d ", numbers[i]); // Print the numbers } return 0; }
fread()
.
fclose()
— Closing a FileAfter all file operations are completed, it's crucial to close the file using fclose()
. This releases the resources used by the file.
int fclose(FILE *stream);
fclose()
#includeint main() { FILE *file = fopen("example.txt", "w"); if (file == NULL) { printf("Error opening file.\n"); return 1; } fprintf(file, "This file will now be closed."); fclose(file); // Close the file printf("File closed successfully.\n"); return 0; }
fclose()
to close the file and free up system resources.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!