I l@ve RuBoard |
![]() ![]() |
16.11 C-Style Binary I/OBinary I/O is accomplished through two routines: std::fread and std::fwrite. The syntax for std::fread is: read_size = std::fread(data_ptr, 1, size, file);
For example: struct { int width; int height; } rectangle; if (std::fread(<static_cast<char *>&rectangle, 1, sizeof(rectangle), in_file) != sizeof(rectangle)) { std::fprintf(stderr, "Unable to read rectangle\n"); exit (8); } In this example you are reading in the structure rectangle. The & operator makes the structure into a pointer. The cast static_cast<char *> turns &rectangle into the proper parameter type, and the sizeof operator is used to determine how many bytes to read in as well as to check that the read was successful. std::fwrite has a calling sequence similar to std::fread: write_size = std::fwrite(data_ptr, 1, size, file); Question 16-4: No matter what filename you give Example 16-9, std::fopen can't find it. Why? Example 16-9. fun-file/fun-file.cpp#include <cstdio> #include <cstdlib> int main( ) { char name[100]; /* name of the file to use */ std::FILE *in_file; /* file for input */ std::printf("Name? "); std::fgets(name, sizeof(name), stdin); in_file = std::fopen(name, "r"); if (in_file == NULL) { std::fprintf(stderr, "Could not open file\n"); exit(8); } std::printf("File found\n"); std::fclose(in_file); return (0); } ![]() |
I l@ve RuBoard |
![]() ![]() |