In this code I am trying to read all the data from the file using the fread() function.
The problem is that nothing is read in the array.
How can fix the error?
#include <stdio.h>
void func(const char *srcFilePath)
{
FILE *pFile = fopen(srcFilePath, "r");
float daBuf[30];
if (pFile == NULL)
{
perror(srcFilePath);
} else {
while (!feof(pFile)) {
fread(daBuf, sizeof(float), 1, pFile);
}
}
for (int i = 0; i < 5; i++) {
printf(" daBuf = %f \n", daBuf[i]);
}
}
void main() {
const char inputfile[] = "/home/debian/progdir/input";
func(inputfile);
}
The input file has values like this:
1.654107,
1.621582,
1.589211,
1.557358,
1.525398,
1.493311,
1.483532,
1.483766,
1.654107,
Your file contains formatted text, so you can use
fscanf.Ensure that you are reading data into a new position in the array every iteration, and that you do not go beyond the bounds of the array.
Use the return value of
fscanfto control your loop.Notice the format string for
fscanfis"%f,".freadis generally intended for binary data, in which case you would open the file with the additional"b"mode.Here is an example, if your file contained binary data: