<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.
FILE
, size_t
, and NULL
#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;
}
fopen()
to open a file in write mode ("w") and then in read mode ("r").fprintf()
is used to write formatted output to the file.fgets()
reads a line from the file into a buffer.fclose()
is called to properly close the file after operations.perror()
is used for error reporting, which prints to stderr.#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;
}
printf()
is used for formatted output to stdout.scanf()
reads formatted input from stdin."%49s %d %f"
specifies the expected input format.scanf()
successfully read all three values.fprintf()
with stderr
is used for error output.#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;
}
Record
struct to demonstrate working with structured data.fwrite()
is used to write binary data to the file.fread()
reads binary data from the file.fread()
returns less than the requested number of items.#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;
}
fseek()
to move the file position indicator.SEEK_SET
, SEEK_CUR
, and SEEK_END
are used to set the reference point for seeking.rewind()
is used to move back to the beginning of the file.Buffer Flushing: Use fflush()
to ensure all buffered data is written to the file.
Error Checking: Always check return values of I/O functions for error conditions.
File Descriptors: fileno()
can be used to get the underlying file descriptor of a FILE*
.
Thread Safety: Many <cstdio>
functions are not thread-safe. Use appropriate synchronization in multi-threaded programs.
Performance: For simple I/O operations, <cstdio>
functions can be faster than C++ streams.
The <cstdio>
header in C++ provides a set of powerful I/O functions inherited from C:
printf
, scanf
, etc.) allow for precise control over input and output formats.fread
, fwrite
) enable efficient handling of binary data.fseek
, ftell
, rewind
) allow for random access in files.perror
and the ferror
macro.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.