Practical Writing Scenarios
Common File Writing Use Cases
1. Logging System Events
#include <time.h>
#include <stdio.h>
void log_event(const char *message) {
FILE *logfile = fopen("/var/log/myapp.log", "a");
time_t now;
time(&now);
fprintf(logfile, "[%s] %s\n", ctime(&now), message);
fclose(logfile);
}
2. Configuration File Management
#include <stdio.h>
void update_config(const char *key, const char *value) {
FILE *config = fopen("/etc/myapp/config.ini", "a+");
fprintf(config, "%s=%s\n", key, value);
fclose(config);
}
File Writing Patterns
graph TD
A[File Writing Scenario] --> B{Write Type}
B --> |Append| C[Logging]
B --> |Overwrite| D[Configuration]
B --> |Atomic| E[Temporary Files]
3. Data Serialization
Scenario |
Method |
Use Case |
CSV Export |
fprintf |
Spreadsheet Data |
JSON Writing |
fprintf |
Configuration |
Binary Serialization |
fwrite |
Structured Data |
4. Atomic File Writing
#include <stdio.h>
#include <unistd.h>
int atomic_write(const char *filename, const char *content) {
char temp_filename[256];
snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", filename);
FILE *temp_file = fopen(temp_filename, "w");
fprintf(temp_file, "%s", content);
fclose(temp_file);
return rename(temp_filename, filename);
}
Error-Resilient Writing Techniques
Safe File Writing Approach
int safe_file_write(const char *path, const char *data) {
FILE *fp = fopen(path, "w");
if (!fp) {
perror("File open error");
return -1;
}
if (fprintf(fp, "%s", data) < 0) {
perror("Write error");
fclose(fp);
return -1;
}
if (fclose(fp) != 0) {
perror("File close error");
return -1;
}
return 0;
}
Buffered Writing for Large Data
void efficient_large_file_write(const char *filename, char **data, int lines) {
FILE *file = fopen(filename, "w");
setvbuf(file, NULL, _IOFBF, 8192); // 8KB buffer
for (int i = 0; i < lines; i++) {
fputs(data[i], file);
}
fclose(file);
}
Best Practices for LabEx Developers
- Always check file operation return values
- Use appropriate file modes
- Implement proper error handling
- Consider file permissions and security
- Close files after operations