cstdio


Include file: <cstdio>

The <cstdio> header is part of the C++ Standard Library and provides input/output operations that are compatible with C-style I/O functions. This header is essentially the C++ version of the C standard <stdio.h> header. It offers a set of functions for file handling, formatted input and output, and general I/O operations. While C++ provides more modern I/O facilities through <iostream>, <cstdio> remains useful for C compatibility, performance-critical code, and certain low-level operations.

Key Characteristics

Example 1: Basic File I/O Operations

#include <cstdio>
#include <cstdlib>

int main() {
    FILE* file = fopen("example.txt", "w");
    if (file == NULL) {
        perror("Error opening file");
        return EXIT_FAILURE;
    }

    fprintf(file, "Hello, World!\n");
    fclose(file);

    file = fopen("example.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return EXIT_FAILURE;
    }

    char buffer[100];
    if (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("Read from file: %s", buffer);
    }

    fclose(file);
    return EXIT_SUCCESS;
}

Explanation:

Example 2: Formatted Input and Output

#include <cstdio>

int main() {
    int age;
    char name[50];
    float height;

    printf("Enter your name, age, and height: ");
    if (scanf("%49s %d %f", name, &age, &height) == 3) {
        printf("Name: %s\nAge: %d\nHeight: %.2f meters\n", name, age, height);
    } else {
        fprintf(stderr, "Error reading input\n");
    }

    return 0;
}

Explanation:

Example 3: Working with Binary Files

#include <cstdio>
#include <cstdint>

struct Record {
    int32_t id;
    char name[50];
    double balance;
};

int main() {
    Record records[] = {
        {1, "Alice", 1000.50},
        {2, "Bob", 2500.75},
        {3, "Charlie", 3750.25}
    };

    FILE* file = fopen("records.bin", "wb");
    if (file == NULL) {
        perror("Error opening file for writing");
        return 1;
    }

    fwrite(records, sizeof(Record), 3, file);
    fclose(file);

    file = fopen("records.bin", "rb");
    if (file == NULL) {
        perror("Error opening file for reading");
        return 1;
    }

    Record readRecord;
    while (fread(&readRecord, sizeof(Record), 1, file) == 1) {
        printf("ID: %d, Name: %s, Balance: %.2f\n", 
               readRecord.id, readRecord.name, readRecord.balance);
    }

    fclose(file);
    return 0;
}

Explanation:

Example 4: File Positioning and Random Access

#include <cstdio>
#include <cstdint>

int main() {
    FILE* file = fopen("random_access.bin", "wb+");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    // Write some integers to the file
    for (int i = 0; i < 10; ++i) {
        int32_t value = i * 10;
        fwrite(&value, sizeof(int32_t), 1, file);
    }

    // Move to a specific position and read
    fseek(file, 5 * sizeof(int32_t), SEEK_SET);
    int32_t value;
    fread(&value, sizeof(int32_t), 1, file);
    printf("Value at position 5: %d\n", value);

    // Move relative to current position and write
    fseek(file, sizeof(int32_t), SEEK_CUR);
    value = 999;
    fwrite(&value, sizeof(int32_t), 1, file);

    // Move to end and append
    fseek(file, 0, SEEK_END);
    value = 100;
    fwrite(&value, sizeof(int32_t), 1, file);

    // Read entire file
    rewind(file);
    while (fread(&value, sizeof(int32_t), 1, file) == 1) {
        printf("%d ", value);
    }
    printf("\n");

    fclose(file);
    return 0;
}

Explanation:

Additional Considerations

  1. Buffer Flushing: Use fflush() to ensure all buffered data is written to the file.

  2. Error Checking: Always check return values of I/O functions for error conditions.

  3. File Descriptors: fileno() can be used to get the underlying file descriptor of a FILE*.

  4. Thread Safety: Many <cstdio> functions are not thread-safe. Use appropriate synchronization in multi-threaded programs.

  5. Performance: For simple I/O operations, <cstdio> functions can be faster than C++ streams.

Summary

The <cstdio> header in C++ provides a set of powerful I/O functions inherited from C:

While C++ provides more type-safe and object-oriented I/O mechanisms through <iostream>, <cstdio> remains valuable for C compatibility, performance-critical code, and certain low-level operations. It's particularly useful when working with binary files, when precise formatting control is needed, or when interfacing with C libraries. However, developers should be aware of potential pitfalls such as buffer overflows and should always perform proper error checking when using these functions.

Related

Previous Page | Course Schedule | Course Content