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

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

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

1,074 Views
sallen881
Contributor I
 

I am working with a pair of Link2 development boards and MCUXpresso IDE V11.7.1. I'm using the newlib semihost library, which has stdio functionality. 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 while debugging. 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;
uint16_t writeData[5] = {1, 2, 3, 4, 5};
uint16_t readData[5] = {0, 0, 0, 0, 0};
uint16_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?

0 Kudos
Reply
3 Replies

992 Views
Habib_MS
NXP Employee
NXP Employee

Hello @sallen881,
In order to support you better, can you provide me which MCU you are currently using?
Also, I understand that you are using the Link2 development boards for debugging, is this correct?
In the other hand, in order to try a pinpoint if this solves the issue, can you use the parameter function of fopen "w+b" to write and read the file with the same instruction. as show this page in "Parameter Values"?
BR
Habib

0 Kudos
Reply

1,065 Views
larrydemuth
Contributor III

Just a thought, try fflush(fp); after your fwrite, and before fclose. 

 

So:

fp = fopen("testFile.dat", "wb");
nData = fwrite(&writeData, sizeof(uint16_t), 5, fp);

fflush(fp);
fclose(fp);

Then do your read.

0 Kudos
Reply

1,061 Views
sallen881
Contributor I
Thanks for the suggestion. I just tried it, no luck. I've also tried rewind(fp) as well as completely removing the write to file section of the code (as the file already exists once the program has been run once). Neither of these worked either, I still get nData = 0 and no change to readData[].
0 Kudos
Reply