0

First I have this:

int main (void)
{
   int m = 10;
   double x[3] = {1.5, -3.5, 3.25};

   int n1, n2; FILE *izTok;
   izTok = fopen ("podaci.bin", "wb");

   n1 = fwrite (&m, sizeof(m), 1, izTok);
   n2 = fwrite (x, sizeof(x[0]), 3, izTok);
   fclose(izTok);

   return 0;
}

And after that I try to read from it with

   FILE *stream;
   stream = fopen("podaci.bin", "r");

   n1 = fread(&n, sizeof(n), 1, stream);
   n2 = fread(arr, sizeof(arr[0]), 3, stream);

   printf("%d %f %f %f", n, arr[0], arr[1], arr[2]);

And regardless of whether I put

 stream = fopen("podaci.bin", "r");

or

 stream = fopen("podaci.bin", "rb");

the output is the same

 10 1.500000 -3.500000 3.250000

Whats the point of the flags if it does the same thing both times?

ditoslav
  • 4,563
  • 10
  • 47
  • 79

3 Answers3

3

On all POSIX systems, the b flag is ignored and has no meaning. From man 3 fopen on a Linux system:

The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-UNIX environments.)

On Windows, b means that the data is read unaltered. Otherwise, Text mode is engaged, which is described here. Among others, line endings are transformed and CTRL+Z is interpreted as end-of-file.

Jonas Schäfer
  • 20,140
  • 5
  • 55
  • 69
1

The difference between text and binary depends on your system. Many of the *nixes make a point that on those systems, there is no difference between them. Windows will, in text mode, convert between "\n" and "\r\n" (adding a byte when writing and subtracting when reading). If you don't happen to have those bytes in your binary data, then you won't notice a difference there either.

tabstop
  • 1,751
  • 11
  • 10
1

The point of the flags is that some Operating Systems treat text and binary streams differently. Yours may not. But it still may: if the double values as binary values contain a byte with value '\r' you may be surprised to find that the numbers you read depend on whether you used "r" or "rb" to open the file.

Jens
  • 69,818
  • 15
  • 125
  • 179