c
examples
examples.c🔧c
/*
* =============================================================================
* WRITING FILES IN C
* Code Examples
* =============================================================================
*
* This file demonstrates various techniques for writing data to files in C.
* Each example is self-contained and can be compiled independently.
*
* Compilation: gcc examples.c -o examples
* =============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
/*
* =============================================================================
* EXAMPLE 1: Writing Characters with fputc()
* =============================================================================
* fputc() writes a single character to a file.
* Returns the character written on success, EOF on error.
*/
void example_fputc(void) {
printf("=== Example 1: Writing Characters with fputc() ===\n\n");
FILE *fp = fopen("char_output.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return;
}
// Write individual characters
char message[] = "Hello, World!";
printf("Writing characters one by one:\n");
for (int i = 0; message[i] != '\0'; i++) {
int result = fputc(message[i], fp);
if (result == EOF) {
perror("Error writing character");
fclose(fp);
return;
}
printf("Wrote: '%c' (ASCII: %d)\n", message[i], message[i]);
}
// Write a newline
fputc('\n', fp);
fclose(fp);
printf("\nFile 'char_output.txt' created successfully.\n\n");
// Verify by reading back
fp = fopen("char_output.txt", "r");
if (fp != NULL) {
printf("Verification - File contents:\n");
int ch;
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
}
printf("\n");
}
/*
* =============================================================================
* EXAMPLE 2: Writing Strings with fputs()
* =============================================================================
* fputs() writes a string to a file (without automatic newline).
* Returns non-negative value on success, EOF on error.
*/
void example_fputs(void) {
printf("=== Example 2: Writing Strings with fputs() ===\n\n");
FILE *fp = fopen("string_output.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return;
}
// Write multiple lines using fputs
// Note: fputs does NOT add newline automatically
char *lines[] = {
"First line of text\n",
"Second line with numbers: 12345\n",
"Third line with special chars: @#$%\n",
"Final line - The End!\n",
NULL // Sentinel to mark end
};
printf("Writing strings to file:\n");
for (int i = 0; lines[i] != NULL; i++) {
if (fputs(lines[i], fp) == EOF) {
perror("Error writing string");
fclose(fp);
return;
}
printf("Wrote: %s", lines[i]);
}
fclose(fp);
printf("\nFile 'string_output.txt' created successfully.\n\n");
// Verify by reading back
fp = fopen("string_output.txt", "r");
if (fp != NULL) {
printf("Verification - File contents:\n");
printf("----------------------------\n");
char buffer[256];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
printf("----------------------------\n");
fclose(fp);
}
printf("\n");
}
/*
* =============================================================================
* EXAMPLE 3: Formatted Output with fprintf()
* =============================================================================
* fprintf() writes formatted data to a file, similar to printf().
* Returns number of characters written on success, negative on error.
*/
void example_fprintf(void) {
printf("=== Example 3: Formatted Output with fprintf() ===\n\n");
FILE *fp = fopen("formatted_output.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return;
}
// Write a formatted report
fprintf(fp, "===========================================\n");
fprintf(fp, " SALES REPORT - Q4 2024 \n");
fprintf(fp, "===========================================\n\n");
// Product data
struct {
char name[30];
int quantity;
float price;
} products[] = {
{"Widget Pro", 150, 29.99},
{"Super Gadget", 75, 49.99},
{"Mega Device", 200, 19.99},
{"Ultra Tool", 50, 99.99}
};
int num_products = sizeof(products) / sizeof(products[0]);
// Write table header
fprintf(fp, "%-20s %10s %12s %15s\n", "Product", "Quantity", "Unit Price", "Total");
fprintf(fp, "%-20s %10s %12s %15s\n", "-------", "--------", "----------", "-----");
float grand_total = 0.0;
for (int i = 0; i < num_products; i++) {
float total = products[i].quantity * products[i].price;
grand_total += total;
fprintf(fp, "%-20s %10d $%11.2f $%14.2f\n",
products[i].name,
products[i].quantity,
products[i].price,
total);
}
fprintf(fp, "\n%-20s %10s %12s $%14.2f\n", "GRAND TOTAL:", "", "", grand_total);
fprintf(fp, "\n===========================================\n");
// Add timestamp
time_t now = time(NULL);
fprintf(fp, "Report generated: %s", ctime(&now));
fclose(fp);
printf("File 'formatted_output.txt' created successfully.\n\n");
// Display the file
fp = fopen("formatted_output.txt", "r");
if (fp != NULL) {
printf("File contents:\n");
char buffer[256];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
fclose(fp);
}
printf("\n");
}
/*
* =============================================================================
* EXAMPLE 4: Writing Binary Data with fwrite()
* =============================================================================
* fwrite() writes binary data to a file.
* Returns number of elements successfully written.
*/
void example_fwrite(void) {
printf("=== Example 4: Writing Binary Data with fwrite() ===\n\n");
// Create sample data
struct Student {
int id;
char name[50];
float gpa;
int age;
};
struct Student students[] = {
{1001, "Alice Johnson", 3.85, 20},
{1002, "Bob Smith", 3.42, 21},
{1003, "Carol Williams", 3.91, 19},
{1004, "David Brown", 3.67, 22},
{1005, "Eva Martinez", 3.78, 20}
};
int num_students = sizeof(students) / sizeof(students[0]);
// Write binary data
FILE *fp = fopen("students.dat", "wb");
if (fp == NULL) {
perror("Error opening file for binary write");
return;
}
// Write number of records first (as header)
fwrite(&num_students, sizeof(int), 1, fp);
// Write student records
size_t written = fwrite(students, sizeof(struct Student), num_students, fp);
printf("Wrote %zu student records to 'students.dat'\n", written);
printf("Total bytes written: %zu\n", sizeof(int) + written * sizeof(struct Student));
fclose(fp);
// Read back and verify
printf("\nVerification - Reading binary data back:\n");
printf("-----------------------------------------\n");
fp = fopen("students.dat", "rb");
if (fp != NULL) {
int count;
fread(&count, sizeof(int), 1, fp);
printf("Number of records: %d\n\n", count);
struct Student s;
printf("%-6s %-20s %6s %4s\n", "ID", "Name", "GPA", "Age");
printf("%-6s %-20s %6s %4s\n", "----", "----", "---", "---");
for (int i = 0; i < count; i++) {
fread(&s, sizeof(struct Student), 1, fp);
printf("%-6d %-20s %6.2f %4d\n", s.id, s.name, s.gpa, s.age);
}
fclose(fp);
}
printf("\n");
}
/*
* =============================================================================
* EXAMPLE 5: Append Mode - Adding to Existing Files
* =============================================================================
* Mode "a" opens file for appending; creates if doesn't exist.
*/
void example_append_mode(void) {
printf("=== Example 5: Append Mode ===\n\n");
const char *filename = "log_file.txt";
// First, create or overwrite the file
FILE *fp = fopen(filename, "w");
if (fp != NULL) {
fprintf(fp, "=== Log Started ===\n");
fclose(fp);
printf("Created new log file.\n");
}
// Now append entries
printf("Appending log entries...\n\n");
for (int i = 1; i <= 5; i++) {
fp = fopen(filename, "a"); // Open in append mode
if (fp == NULL) {
perror("Error opening file for append");
return;
}
time_t now = time(NULL);
struct tm *tm_info = localtime(&now);
char time_str[26];
strftime(time_str, 26, "%Y-%m-%d %H:%M:%S", tm_info);
fprintf(fp, "[%s] Log entry #%d: System status OK\n", time_str, i);
fclose(fp);
printf("Appended entry #%d\n", i);
// Small delay to see different timestamps
// (In real code, you wouldn't do this)
}
// Final append
fp = fopen(filename, "a");
if (fp != NULL) {
fprintf(fp, "=== Log Ended ===\n");
fclose(fp);
}
// Display the file
printf("\nFile contents:\n");
printf("--------------\n");
fp = fopen(filename, "r");
if (fp != NULL) {
char buffer[256];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
fclose(fp);
}
printf("\n");
}
/*
* =============================================================================
* EXAMPLE 6: Error Handling in File Writing
* =============================================================================
* Demonstrating proper error checking when writing files.
*/
void example_error_handling(void) {
printf("=== Example 6: Error Handling in File Writing ===\n\n");
// Example 1: Check for write errors
const char *filename = "error_test.txt";
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
fprintf(stderr, "ERROR: Cannot open '%s': %s\n", filename, strerror(errno));
return;
}
// Write some data
const char *data = "This is a test of error handling.\n";
if (fprintf(fp, "%s", data) < 0) {
fprintf(stderr, "ERROR: Write failed: %s\n", strerror(errno));
fclose(fp);
return;
}
// Check for errors using ferror()
if (ferror(fp)) {
fprintf(stderr, "ERROR: A file error occurred\n");
clearerr(fp); // Clear error indicator
}
// Check fclose for errors (important for buffered I/O)
if (fclose(fp) != 0) {
fprintf(stderr, "ERROR: Failed to close file: %s\n", strerror(errno));
return;
}
printf("File written and closed successfully.\n");
// Example 2: Writing to read-only directory (will fail)
printf("\nAttempting to write to non-existent directory:\n");
FILE *fp2 = fopen("/nonexistent_dir/test.txt", "w");
if (fp2 == NULL) {
fprintf(stderr, "Expected error: %s\n", strerror(errno));
} else {
fclose(fp2);
}
printf("\n");
}
/*
* =============================================================================
* EXAMPLE 7: Buffering Control with setbuf() and setvbuf()
* =============================================================================
* Control how output is buffered before being written.
*/
void example_buffering(void) {
printf("=== Example 7: Buffering Control ===\n\n");
// Example 1: No buffering (immediate write)
printf("Creating unbuffered file...\n");
FILE *fp1 = fopen("unbuffered.txt", "w");
if (fp1 != NULL) {
setbuf(fp1, NULL); // Disable buffering
fprintf(fp1, "Line 1: This is written immediately\n");
fprintf(fp1, "Line 2: No waiting for buffer to fill\n");
fprintf(fp1, "Line 3: Each write goes directly to file\n");
fclose(fp1);
printf("Unbuffered file created.\n");
}
// Example 2: Line buffering
printf("\nCreating line-buffered file...\n");
FILE *fp2 = fopen("line_buffered.txt", "w");
if (fp2 != NULL) {
// _IOLBF = line buffered
setvbuf(fp2, NULL, _IOLBF, 0);
fprintf(fp2, "Line 1: Flushed when newline is written\n");
fprintf(fp2, "Line 2: Good for log files\n");
fprintf(fp2, "Line 3: Interactive output\n");
fclose(fp2);
printf("Line-buffered file created.\n");
}
// Example 3: Full buffering with custom size
printf("\nCreating fully-buffered file with 1KB buffer...\n");
FILE *fp3 = fopen("full_buffered.txt", "w");
if (fp3 != NULL) {
char *buffer = malloc(1024); // 1KB buffer
if (buffer != NULL) {
// _IOFBF = fully buffered
setvbuf(fp3, buffer, _IOFBF, 1024);
// Write lots of small data
for (int i = 0; i < 100; i++) {
fprintf(fp3, "Line %d: This is buffered until 1KB is reached\n", i + 1);
}
fclose(fp3); // Buffer is flushed on close
free(buffer);
printf("Fully-buffered file created.\n");
}
}
// Example 4: Manual flushing
printf("\nDemonstrating manual flushing...\n");
FILE *fp4 = fopen("manual_flush.txt", "w");
if (fp4 != NULL) {
fprintf(fp4, "Data written but might be in buffer...\n");
fflush(fp4); // Force write to disk
printf("Data flushed to disk.\n");
fprintf(fp4, "More data...\n");
fflush(fp4);
fclose(fp4);
}
printf("\nAll buffer examples completed.\n\n");
}
/*
* =============================================================================
* EXAMPLE 8: Writing Arrays and Blocks of Data
* =============================================================================
* Efficiently writing large amounts of data.
*/
void example_write_arrays(void) {
printf("=== Example 8: Writing Arrays and Blocks ===\n\n");
// Create sample data
#define ARRAY_SIZE 1000
int numbers[ARRAY_SIZE];
// Initialize array
for (int i = 0; i < ARRAY_SIZE; i++) {
numbers[i] = i * 2; // Even numbers
}
// Write entire array at once
FILE *fp = fopen("numbers.bin", "wb");
if (fp == NULL) {
perror("Error opening file");
return;
}
size_t elements_written = fwrite(numbers, sizeof(int), ARRAY_SIZE, fp);
printf("Wrote %zu integers (%zu bytes)\n", elements_written, elements_written * sizeof(int));
fclose(fp);
// Verify by reading back
printf("\nVerification (first 10 and last 10 elements):\n");
fp = fopen("numbers.bin", "rb");
if (fp != NULL) {
int read_numbers[ARRAY_SIZE];
fread(read_numbers, sizeof(int), ARRAY_SIZE, fp);
printf("First 10: ");
for (int i = 0; i < 10; i++) {
printf("%d ", read_numbers[i]);
}
printf("\nLast 10: ");
for (int i = ARRAY_SIZE - 10; i < ARRAY_SIZE; i++) {
printf("%d ", read_numbers[i]);
}
printf("\n");
fclose(fp);
}
// Write 2D array (matrix)
printf("\nWriting 2D matrix to file...\n");
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
fp = fopen("matrix.txt", "w");
if (fp != NULL) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
fprintf(fp, "%4d ", matrix[i][j]);
}
fprintf(fp, "\n");
}
fclose(fp);
printf("Matrix written to 'matrix.txt'\n");
}
printf("\n");
}
/*
* =============================================================================
* EXAMPLE 9: CSV File Generation
* =============================================================================
* Creating properly formatted CSV files.
*/
void example_csv_generation(void) {
printf("=== Example 9: CSV File Generation ===\n\n");
struct Employee {
int id;
char name[50];
char department[30];
float salary;
int years;
};
struct Employee employees[] = {
{101, "John Doe", "Engineering", 75000.00, 5},
{102, "Jane Smith", "Marketing", 65000.00, 3},
{103, "Bob Johnson", "Sales", 55000.00, 7},
{104, "Alice Williams", "Engineering", 80000.00, 8},
{105, "Charlie Brown, Jr.", "HR", 60000.00, 2} // Note: name contains comma
};
int num_employees = sizeof(employees) / sizeof(employees[0]);
FILE *fp = fopen("employees.csv", "w");
if (fp == NULL) {
perror("Error creating CSV file");
return;
}
// Write CSV header
fprintf(fp, "ID,Name,Department,Salary,Years\n");
// Write data rows
for (int i = 0; i < num_employees; i++) {
// Handle names with commas by quoting them
if (strchr(employees[i].name, ',') != NULL) {
fprintf(fp, "%d,\"%s\",%s,%.2f,%d\n",
employees[i].id,
employees[i].name,
employees[i].department,
employees[i].salary,
employees[i].years);
} else {
fprintf(fp, "%d,%s,%s,%.2f,%d\n",
employees[i].id,
employees[i].name,
employees[i].department,
employees[i].salary,
employees[i].years);
}
}
fclose(fp);
printf("CSV file 'employees.csv' created.\n\n");
// Display the file
printf("CSV Contents:\n");
printf("-------------\n");
fp = fopen("employees.csv", "r");
if (fp != NULL) {
char buffer[256];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
fclose(fp);
}
printf("\n");
}
/*
* =============================================================================
* EXAMPLE 10: Configuration File Writer
* =============================================================================
* Writing configuration files in INI format.
*/
void example_config_writer(void) {
printf("=== Example 10: Configuration File Writer ===\n\n");
FILE *fp = fopen("app_config.ini", "w");
if (fp == NULL) {
perror("Error creating config file");
return;
}
// Write header comment
fprintf(fp, "; Application Configuration File\n");
fprintf(fp, "; Generated automatically\n");
fprintf(fp, "; Last modified: %s\n\n", __DATE__);
// Write [General] section
fprintf(fp, "[General]\n");
fprintf(fp, "AppName=MyApplication\n");
fprintf(fp, "Version=2.0.1\n");
fprintf(fp, "Language=English\n");
fprintf(fp, "Theme=Dark\n\n");
// Write [Database] section
fprintf(fp, "[Database]\n");
fprintf(fp, "Host=localhost\n");
fprintf(fp, "Port=5432\n");
fprintf(fp, "Name=myapp_db\n");
fprintf(fp, "MaxConnections=100\n");
fprintf(fp, "Timeout=30\n\n");
// Write [Logging] section
fprintf(fp, "[Logging]\n");
fprintf(fp, "Enabled=true\n");
fprintf(fp, "Level=INFO\n");
fprintf(fp, "LogFile=/var/log/myapp.log\n");
fprintf(fp, "MaxSize=10MB\n");
fprintf(fp, "RotationCount=5\n\n");
// Write [Security] section
fprintf(fp, "[Security]\n");
fprintf(fp, "EnableSSL=true\n");
fprintf(fp, "CertPath=/etc/ssl/certs/myapp.crt\n");
fprintf(fp, "KeyPath=/etc/ssl/private/myapp.key\n");
fprintf(fp, "SessionTimeout=3600\n");
fclose(fp);
printf("Configuration file 'app_config.ini' created.\n\n");
// Display the file
printf("Configuration Contents:\n");
printf("-----------------------\n");
fp = fopen("app_config.ini", "r");
if (fp != NULL) {
char buffer[256];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
fclose(fp);
}
printf("\n");
}
/*
* =============================================================================
* EXAMPLE 11: putc() and putw() Functions
* =============================================================================
* Alternative functions for writing characters and integers.
*/
void example_putc_putw(void) {
printf("=== Example 11: putc() and Alternative Functions ===\n\n");
// putc() - similar to fputc() but may be a macro
FILE *fp = fopen("putc_test.txt", "w");
if (fp != NULL) {
char message[] = "Written with putc!";
printf("Using putc() to write: \"%s\"\n", message);
for (int i = 0; message[i] != '\0'; i++) {
putc(message[i], fp);
}
putc('\n', fp);
fclose(fp);
}
// Verify
fp = fopen("putc_test.txt", "r");
if (fp != NULL) {
printf("Read back: ");
int ch;
while ((ch = getc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
}
printf("\nNote: putc() is often a macro for speed, fputc() is always a function.\n");
printf(" Use fputc() when you need to pass it as a function pointer.\n\n");
}
/*
* =============================================================================
* EXAMPLE 12: Writing to Multiple Files Simultaneously
* =============================================================================
* Managing multiple file handles at once.
*/
void example_multiple_files(void) {
printf("=== Example 12: Writing to Multiple Files ===\n\n");
FILE *log_info = fopen("log_info.txt", "w");
FILE *log_warn = fopen("log_warn.txt", "w");
FILE *log_error = fopen("log_error.txt", "w");
if (log_info == NULL || log_warn == NULL || log_error == NULL) {
perror("Error opening log files");
if (log_info) fclose(log_info);
if (log_warn) fclose(log_warn);
if (log_error) fclose(log_error);
return;
}
// Simulated log messages
struct LogEntry {
char level[10];
char message[100];
};
struct LogEntry entries[] = {
{"INFO", "Application started"},
{"INFO", "Loading configuration"},
{"WARN", "Config file not found, using defaults"},
{"INFO", "Database connection established"},
{"ERROR", "Failed to load user preferences"},
{"WARN", "Memory usage above 80%"},
{"INFO", "Processing user request"},
{"ERROR", "Network timeout occurred"},
{"INFO", "Request completed successfully"}
};
int num_entries = sizeof(entries) / sizeof(entries[0]);
printf("Distributing log entries to separate files:\n\n");
for (int i = 0; i < num_entries; i++) {
FILE *target = NULL;
if (strcmp(entries[i].level, "INFO") == 0) {
target = log_info;
} else if (strcmp(entries[i].level, "WARN") == 0) {
target = log_warn;
} else if (strcmp(entries[i].level, "ERROR") == 0) {
target = log_error;
}
if (target != NULL) {
fprintf(target, "[%s] %s\n", entries[i].level, entries[i].message);
printf("Wrote to log_%s.txt: %s\n",
strcmp(entries[i].level, "INFO") == 0 ? "info" :
strcmp(entries[i].level, "WARN") == 0 ? "warn" : "error",
entries[i].message);
}
}
fclose(log_info);
fclose(log_warn);
fclose(log_error);
printf("\nLog files created successfully.\n\n");
}
/*
* =============================================================================
* EXAMPLE 13: Using snprintf() for Safe String Building
* =============================================================================
* Building strings safely before writing to files.
*/
void example_snprintf_build(void) {
printf("=== Example 13: Safe String Building with snprintf() ===\n\n");
char buffer[256];
FILE *fp = fopen("formatted_output2.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return;
}
// Build formatted strings safely
struct Record {
int id;
char name[30];
float value;
};
struct Record records[] = {
{1, "Alpha", 123.456},
{2, "Beta", 789.012},
{3, "Gamma", 345.678}
};
for (int i = 0; i < 3; i++) {
// Build string with bounds checking
int len = snprintf(buffer, sizeof(buffer),
"Record %d: Name=%-10s Value=%10.3f\n",
records[i].id, records[i].name, records[i].value);
if (len >= 0 && len < (int)sizeof(buffer)) {
// String was built successfully, write it
fputs(buffer, fp);
printf("Built and wrote: %s", buffer);
} else {
fprintf(stderr, "Warning: String truncated for record %d\n", records[i].id);
}
}
fclose(fp);
printf("\nFile created with safely formatted strings.\n\n");
}
/*
* =============================================================================
* EXAMPLE 14: Temporary Files
* =============================================================================
* Creating and using temporary files.
*/
void example_temp_files(void) {
printf("=== Example 14: Temporary Files ===\n\n");
// Method 1: tmpfile() - creates a temporary file that is automatically deleted
printf("Method 1: Using tmpfile()\n");
FILE *temp = tmpfile();
if (temp != NULL) {
fprintf(temp, "This is temporary data\n");
fprintf(temp, "It will be deleted when closed\n");
// Seek back to beginning to read
rewind(temp);
char buffer[100];
printf("Reading from temp file:\n");
while (fgets(buffer, sizeof(buffer), temp) != NULL) {
printf(" %s", buffer);
}
fclose(temp); // File is automatically deleted
printf("Temp file closed and deleted.\n\n");
}
// Method 2: tmpnam() - generates a unique filename
printf("Method 2: Using tmpnam()\n");
char temp_filename[L_tmpnam];
if (tmpnam(temp_filename) != NULL) {
printf("Generated temp filename: %s\n", temp_filename);
FILE *fp = fopen(temp_filename, "w");
if (fp != NULL) {
fprintf(fp, "Data in named temporary file\n");
fclose(fp);
printf("File created. Remember to delete it manually!\n");
// Clean up
remove(temp_filename);
printf("File deleted.\n");
}
}
printf("\n");
}
/*
* =============================================================================
* EXAMPLE 15: Complete File Writing Workflow
* =============================================================================
* A comprehensive example showing best practices.
*/
void example_complete_workflow(void) {
printf("=== Example 15: Complete File Writing Workflow ===\n\n");
const char *filename = "complete_example.txt";
FILE *fp = NULL;
int success = 1;
// Step 1: Open file with error checking
printf("Step 1: Opening file '%s'...\n", filename);
fp = fopen(filename, "w");
if (fp == NULL) {
fprintf(stderr, "Failed to open file: %s\n", strerror(errno));
return;
}
printf(" File opened successfully.\n");
// Step 2: Configure buffering (optional)
printf("Step 2: Configuring buffering...\n");
if (setvbuf(fp, NULL, _IOFBF, 4096) != 0) {
fprintf(stderr, "Warning: Could not set buffer\n");
}
printf(" Buffering configured.\n");
// Step 3: Write data with error checking
printf("Step 3: Writing data...\n");
const char *header = "=== Important Data File ===\n\n";
if (fprintf(fp, "%s", header) < 0) {
fprintf(stderr, "Error writing header\n");
success = 0;
}
for (int i = 1; i <= 10 && success; i++) {
if (fprintf(fp, "Entry %d: Data value = %d\n", i, i * 100) < 0) {
fprintf(stderr, "Error writing entry %d\n", i);
success = 0;
}
}
if (success) {
printf(" Data written successfully.\n");
}
// Step 4: Check for any stream errors
printf("Step 4: Checking for errors...\n");
if (ferror(fp)) {
fprintf(stderr, "Stream error detected\n");
success = 0;
} else {
printf(" No stream errors.\n");
}
// Step 5: Flush buffer before closing
printf("Step 5: Flushing buffer...\n");
if (fflush(fp) != 0) {
fprintf(stderr, "Error flushing buffer: %s\n", strerror(errno));
success = 0;
} else {
printf(" Buffer flushed.\n");
}
// Step 6: Close file with error checking
printf("Step 6: Closing file...\n");
if (fclose(fp) != 0) {
fprintf(stderr, "Error closing file: %s\n", strerror(errno));
success = 0;
} else {
printf(" File closed.\n");
}
// Step 7: Report final status
printf("\nWorkflow completed %s.\n", success ? "successfully" : "with errors");
if (success) {
// Show the file contents
printf("\nFile contents:\n");
printf("--------------\n");
fp = fopen(filename, "r");
if (fp != NULL) {
char buffer[256];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
fclose(fp);
}
}
printf("\n");
}
/*
* =============================================================================
* MAIN FUNCTION - Run All Examples
* =============================================================================
*/
int main(void) {
printf("\n");
printf("╔═══════════════════════════════════════════════════════════════╗\n");
printf("║ WRITING FILES IN C - CODE EXAMPLES ║\n");
printf("╚═══════════════════════════════════════════════════════════════╝\n\n");
example_fputc();
example_fputs();
example_fprintf();
example_fwrite();
example_append_mode();
example_error_handling();
example_buffering();
example_write_arrays();
example_csv_generation();
example_config_writer();
example_putc_putw();
example_multiple_files();
example_snprintf_build();
example_temp_files();
example_complete_workflow();
printf("╔═══════════════════════════════════════════════════════════════╗\n");
printf("║ ALL EXAMPLES COMPLETED ║\n");
printf("╚═══════════════════════════════════════════════════════════════╝\n\n");
return 0;
}