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,
2
Answers
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
fscanf
to control your loop.Notice the format string for
fscanf
is"%f,"
.fread
is 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:
You may be confusing
binary representation
andascii representation
of number. Here is a small code to generate a binary file using the
first 5 data in your
input
file.If you compile and execute it, a file
output.bin
will be generated.As you seem to be working on debian, try
xxd
command to dumpthe binary file:
The first 4-byte data
c7b9d33f
corresponds to the first number1.654107
. (Note the byte order depends on the endianness of theprocessor architecture.)
In general we don’t care what
c7b9d33f
means because binary datais not human readable. If you are interested in the format, search google
for
IEEE754
. The important thing isfread()
andfwrite()
aredesigned to read/write binary data.
Your posted program can be used to read
output.bin
with somecorrections:
Output:
You still have a mistake in the usage of
fread()
. You arepassing the fixed address
daBuf
tofread()
in the loopas
fread(daBuf, sizeof(float), 1, pFile)
. It just modifies thefirst element daBuf[0] repeatedly without assigning other elements.
You can read multiple elements of data at once by passing the length
as the 3rd argument to fread().
As you may have roughly grasped the binary data, let’s go back to
ascii data. Try to dump your
input
(w/o commas) withxxd
:If you read the file
input
by usingfread()
, the first elementdaBuf[0], for instance, will be assigned to 4-byte data
312e3635
,which will be meaningless as a binary representation.
I hope you will have understood why you cannot use
fread()
toread ascii files.