Writing a file in C involves using the standard library functions to open the file, write data to it, and then close it.
Opens a file for writing
You can opens a file for writing through “w” mode.
Syntax:
FILE *fopen(const char *filename, const char *mode);
Explanation:
- filename is the name of the file to open.
- mode specifies the access mode (write, append, etc.).
Example:
#include <stdio.h>
int main() {
// Open the file for writing
FILE *file = fopen("main.txt", "w");
if (file == NULL) {
// Check if the file could not be opened
printf("Error opening file for writing.\n");
return 1; // Exit with an error code
}
// Writing a string to the file using fputs()
fputs("This is an example of writing to a file in C.\n", file);
// Writing a single character to the file using fputc()
fputc('B', file);
// Writing formatted data to the file using fprintf()
fprintf(file, "This is a number: %d\n", 42);
// Close the file after writing
fclose(file);
printf("Data has been written to the file successfully.\n");
return 0;
}
Code Explanation:
- fopen(“main.txt”, “w”): This opens the file main.txt in write mode. If the file doesn’t exist, it will be created. If it already exists, it will be truncated (emptied).
- fputs(): Writes a string to the file. The string is written exactly as it is.
- fputc(): Writes a single character to the file.
- fprintf(): Writes formatted data to the file, similar to printf(), but the output goes to the file instead of the console.
- fclose(file): Closes the file after all writing operations are completed.
fwrite() method
The fwrite() function in C is used to write binary data to a file. It writes a specified number of bytes from a given memory buffer to a file. It is particularly useful when working with binary files, such as saving data structures or arrays in their raw binary format.
Syntax:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
Explanation:
ptr: A pointer to the data you want to write (usually an array or a structure).
size: The size of each element to be written (e.g., the size of a char, int, or a structure).
count: The number of elements to write (i.e., how many size-sized elements to write).
stream: The file pointer (opened with fopen()) to the file where you want to write the data.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("main.bin", "wb");
if (file == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
// Array of integers to write to the file
int numbers[] = {1, 2, 3, 4};
// Writing the array to the file
size_t elements_written = fwrite(numbers, sizeof(int), 4, file);
if (elements_written == 4) {
printf("Successfully written 4 integers to the file.\n");
} else {
printf("Error writing to the file.\n");
}
// Close the file
fclose(file);
return 0;
}