Shane Allen
Shane Allen

Reputation: 11

Why is fread() not working, but fwrite() works fine?

I am working with an NXP microcontroller, which has stdio functionality when connected to the debugger. I've had no issues using fwrite() to write data to a binary file, so that I can monitor and plot values with an external program. I'm now trying to go the other way, but I can't get fread() to work. I've reduced the code to the simplest example I can think of, and it still doesn't read the file:

#include <stdio.h>

int main (void)
{
  FILE *fp;
  int16_t writeData[5] = {1, 2, 3, 4, 5};
  int16_t readData[5] = {0, 0, 0, 0, 0};
  int16_t nData;

  // write to file
  fp = fopen("testFile.dat", "wb");
  nData = fwrite(&writeData, sizeof(uint16_t), 5, fp);
  fclose(fp);

  // read from file
  fp = fopen("testFile.dat", "rb");
  nData = fread(&readData, sizeof(uint16_t), 5, fp);
  fclose(fp);
}

I'm stepping through the code line-by-line. after writing the file, nData = 5 and the file contents are as expected "01 00 02 00 03 00 04 00 05 00" (observed using Windows PowerShell command format-hex "testFile.dat"). After reading the file, nData = 0 and readData is not changed.

I've checked if (fp = NULL) after calling fopen(), that's not the issue. I've tried calling ferror(fp) after each line in the read section, it always returns 0. I've also had no luck with the agruments readData, &readData[0], and readData[0] (doesn't make sense/seem necessary respectively, but I've seen these variations in some examples). The "required supporting OS subroutines" are the same for both fread() and fwrite(), so that's not the issue either.

Any suggestions?

Upvotes: 1

Views: 76

Answers (1)

john doe
john doe

Reputation: 11

  • To be sure the correct byte size is used:

try:

(sizeof(int16_t)

instead of

sizeof(uint16_t))
  • return values should be checked.
  • Error checking is also a good practice.

Upvotes: 1

Related Questions