gpt4 book ai didi

c - 需要有关fread()的帮助

转载 作者:行者123 更新时间:2023-11-30 19:48:32 26 4
gpt4 key购买 nike

我正在尝试读取一个包含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;
}

最佳答案

我敢打赌,您不是在读取二进制文件。

尝试这个 :

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)是否打开失败。

关于c - 需要有关fread()的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18049788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com