0

I am working on a project that requires quick file input and output so I decided to use fread/fwrite. Fread works as intended but fwrite prints extra, random characters and I am not sure what the problem is.

    for (int i = 0; i < vector.size(); ++i)
    {
        fwrite(&vector[i], vector.size(), sizeof(int), outfile);
        fwrite("\n", 1, sizeof(char), outfile);
    }

vector is of type int and in the first test case the output is expected to be from top-bottom:
3
2
1

The file does print it that way but it adds extra characters and thus it looks like so:

û° 3 ÌÌÌÌÌÌ
àý° 2 ÌÌÌÌÌÌ
xû° 1 ÌÌÌÌÌÌ

Any idea what might be wrong with the file output?

iaminsensible
  • 123
  • 1
  • 8
  • 1
    Do you want a binary file or text? – drescherjm Dec 05 '19 at 23:48
  • I am looking to print on a text file which I now understand is not possible with fwrite? – iaminsensible Dec 05 '19 at 23:50
  • You are doing a bit of binary and text. You write the internal memory representation (probably 4 or 8 bytes and likely little endian but could be big endian if you are not on an x86 CPU) of an int in your system then you try to add "\n" between items. – drescherjm Dec 05 '19 at 23:52

1 Answers1

0

To start, your arguments are in the incorrect order. See the documentation for fwrite. Also, fwrite may not necessarily be what you want. I'd refer to that documentation for more info. That being said...

size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );

Given this signature, your first line there should read: fwrite(&vector[i], sizeof(int), 1, outfile);

So you aren't writing sizeof(int) (likely 4 or 8) ints every time, versus 1.

To explain a bit more, the way you wrote it would be writing 3-byte-wide entries X sizeof(int) times from the given address every single time, which would be going out of bounds and causing undefined behavior.

Ricky Mutschlechner
  • 4,291
  • 2
  • 31
  • 36