Writing to Files in C
Writing data to files allows you to store output generated by your program. C provides several functions for writing to files.
1. Functions to Write to Files
Function | Description |
---|---|
fprintf(FILE *fp, const char *format, ...) | Writes formatted output to a file. |
fputs(const char *str, FILE *fp) | Writes a string to a file. |
fputc(int char, FILE *fp) | Writes a character to a file. |
fwrite(const void *ptr, size_t size, size_t nmemb, FILE *fp) | Writes data from an array to a file. |
2. Example: Writing Text to a File
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fptr;
fptr = fopen("output.txt", "w");
if (fptr == NULL) {
printf("Error opening file!\n");
exit(1);
}
fprintf(fptr, "This is a line of text.\n");
fputs("This is another line.\n", fptr);
fclose(fptr);
printf("Data written to file successfully.\n");
return 0;
}
3. Example: Writing Binary Data to a File
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fptr;
int numbers[] = {1, 2, 3, 4, 5};
fptr = fopen("data.bin", "wb");
if (fptr == NULL) {
printf("Error opening file!\n");
exit(1);
}
fwrite(numbers, sizeof(int), 5, fptr);
fclose(fptr);
printf("Binary data written to file successfully.\n");
return 0;
}
Best Practices
- Use
fprintf()
for formatted text output. - Ensure the file is opened in the correct mode (e.g.,
"w"
for writing). - Check the return value of writing functions for errors.
Don'ts
- Don't forget to flush buffers if necessary using
fflush()
. - Don't assume data is written immediately; buffering may delay writing.
- Don't neglect to close the file after writing.
Key Takeaways
- Writing to files is essential for data persistence.
- Different functions are available for writing text and binary data.
- Proper error handling ensures data integrity.