16.11 C-Style Binary IO

I l @ ve RuBoard

16.11 C-Style Binary I/O

Binary 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)   ; 
read_size

Size of the data that was read. If this is less than size , an end-of-file or error occurred.

data_ptr

Pointer to a buffer to receive the data being read.

1

The constant 1. (For the reason behind this constant, see the sidebar.)

size

Number of bytes to be read.

file

Input file.

Why 1?

If you look at the documentation for std::fread or std::fwrite , you'll see that it the number of bytes to read is specified as two parameters. These two are multiplied together to determine the number of bytes to actually read. For example, to read 12 bytes you could write:

 std::fread(in_file, 3, 4, buffer) 

The logic behind this system is that if you are reading in an array, you could specify the size of an element (parameter #2) and the number of elements to read (parameter #4). The function would then return the number of elements read, not the number of bytes.

Since every almost every other standard C and C++ function that deals with memory deals with byte sizes, it's much easier to put a 1 in for parameter #2 and a byte size in for #3 and not have to worry about array elements.

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


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net