1

I'm trying to write some bytes array into a file using fwrite() in c. The code is as following

typedef unsigned char byte;
byte buffer[100];
generate_n(buffer, 48, rand);
int numByte = 48;
file = fopen("test", "wb+");
fwrite(buffer, sizeof(byte), numByte, file);

I checked numByte value and the file written. But sometimes the file size is numByte + 1 bytes. Not always, but sometimes. It's very strange. Could anyone help me? Thanks in advance.

ps. Some people said that they can't understand this happens sometimes, not always, but it is really true. Sometimes fwrite() writes 48 bytes, sometimes it writes 49bytes. I can't understand, too.

superuser123
  • 151
  • 1
  • 1
  • 12
  • 2
    Does this exact code exhibit the described behavior? This is not enough to tell you what's wrong, please post how you declare and populate buffer and how did you determine `numByte`, also `byte` is not a base type so please also post what it is. Note that *Not always, but sometimes* appears to be *Undefined Behavior*, which is not possible to know from this code. – Iharob Al Asimi Nov 18 '15 at 01:35
  • 2
    See [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). It's now impossible to tell what's wrong. – roeland Nov 18 '15 at 01:46
  • Who is the *close()* vote? That is ridiculous without giving an opportunity to edit. A couple of minutes is insufficient time. – David C. Rankin Nov 18 '15 at 02:09
  • Have you checked the value returned by `fwrite()`? Did it confirm that it returned greater than `numByte`? Have you checked if anywhere in the program there might be some `fwrite()` calls? – alvits Nov 18 '15 at 02:22
  • Write a parallel file in text mode with the values as text. Then it should be easy to determine if the extra byte is occurring always at the beginning, end after a `'\n`, or Ctrl-Z, and _what_ that extra value may be. Potential issue, UB in another part of code. Like in `generate_n()`. – chux - Reinstate Monica Nov 18 '15 at 03:00
  • How are you checking the file size, exactly? And what OS/filesystem are you using? – rici Nov 18 '15 at 03:10
  • I checked the file size in bytes with just the file. And I'm using Windows. – superuser123 Nov 18 '15 at 05:48
  • Possible duplicate of [Why is fwrite writing more than I tell it to?](https://stackoverflow.com/questions/1586421/why-is-fwrite-writing-more-than-i-tell-it-to) – tommyk Aug 08 '17 at 14:50

0 Answers0