gpt4 book ai didi

c - 从文件加载数组

转载 作者:行者123 更新时间:2023-11-30 14:56:57 25 4
gpt4 key购买 nike

我正在使用fwrite保存数组的元素我正在尝试使用 fread 将以前保存的数据加载到数组中。返回值fread非零,这意味着它是成功的。但是当我打印数组时,它是空的,没有任何内容被打印。我已将数组保存到文件中

fwrite(num, sizeof(int), k, q); //num is the same array, k=no of elements, q is the file pointer

这是我的代码:

int num[50], NoOfElement;
FILE *p;
if(p = fopen("data.txt", "rb") == NULL)
{
printf("Error");
exit(1);
}
fseek(p, 0, SEEK_END);
NoOfElement = ftell(p) / sizeof(int); //no of elements in the file
fseek(p, 0, SEEK_SET);
fread(num, sizeof(int), NoOfElement, p);

最佳答案

你的代码看起来不错。这个演示程序对我来说工作正常:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num[50], NoOfElement;
FILE *P;
int i;

// Generate test data
for (i = 0; i < 5; ++i)
num[i] = i+1;

// Write test data
P = fopen("data.txt", "wb");
fwrite(num, sizeof(int), 5, P);
fclose(P);

// Overwrite the test data so we know we read it OK
for (i = 0; i < 5; ++i)
num[i] = -1;

// Your code for reading test data
if((P = fopen("data.txt", "rb")) == NULL)
{
printf("Error");
exit(1);
}
fseek(P, 0, SEEK_END);
NoOfElement = ftell(P) / sizeof(int); //no of elements in the file
fseek(P, 0, SEEK_SET);
fread(num, sizeof(int), NoOfElement, P);

// Output test data (shows 1 -> 5 as expected)
for (i = 0; i < NoOfElement; ++i)
printf("%d\n", num[i]);
}

关于c - 从文件加载数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44249310/

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