我正在尝试读取包含20个随机数的二进制文件。虽然文件似乎在读取,但当我尝试将文件内容输出到屏幕时,我只会得到零。
我知道有20个数字,范围从1.00到9,999.99。任何帮助将不胜感激!
#include <stdio.h>
int main()
{
int i; //counter
FILE *file; // file pointer
double fileContents[20] = {0.0};
file = fopen("numbers.bin", "rb"); // open resfile1.bin in read binary mode
if (file == EOF)
{
printf("Error: Unable to open file.\n\n");
exit(1); // exit app
}
else
printf("File successfully opened.\n\n");
/**
fileContents = the array that holds the values read in from fread
sizeof(double) = the size of the data being read in
20 = the number of things to read in
file = the pointer to the file we've opened
**/
fread(fileContents, sizeof(double), 20, file); // does nothing as far as I can tell
for (i=0; i<20; i++)
printf("%d: %lf\n", i, fileContents[i]); // displays contents
fclose(file); // close file
return 0;
}
答案 0 :(得分:0)
我打赌你不是在读二进制文件。
试试这个:
idx=0;
float fileContents[20] = {0.0};
while(!feof(file))
fscanf (file, "%f", &fileContents[idx++]);
for (i=0; i<idx; i++)
printf("%d: %lf\n", i, fileContents[i]);
另外,请检查if (file == NULL)
是否打开失败。