我写了动态数组到文件。(100宽)我从文件中读取它。
但我意识到我无法从内存中读取malloc所有元素。
我的代码示例如下:
main()
{
FILE *file;
int *numbers;
int *numbers2;
numbers = (int *)malloc(100*sizeof(int));
numbers2 = (int *)malloc(100*sizeof(int));
int i,j,tane;
file=fopen("numbers.txt","w++");
for(i=0;i<100;i++)
{ numbers[i]=i;}
if(file==NULL)
{printf("Error:File cannot open \n");
return 1;
}
else {
fwrite(numbers,4,100,file);
}
rewind(file);
printf("Numbers read from file:\n");
tane=fread(numbers2,4,100,file);
for(i=0;i<tane;i++)
{ printf("%d ",numbers2[i]);}
fclose(file);
getch();
}
我看到C打印的0-25个元素。 我无法理解所有元素都不会打印。(0到100)
你能帮我吗?
最诚挚的问候......
答案 0 :(得分:2)
您正在 text 模式下打开文件,但您正在编写二进制数据。请改为fopen("numbers.txt", "wb+")
。
答案 1 :(得分:1)
我猜你实现中的sizeof (int)
不是4。
我很确定它是sizeof (int)
。尝试使用sizeof (int)
而不是魔术常量。更好的方法是将对象本身用作sizeof
...
fwrite(numbers, sizeof *numbers, 100, file);
/* also get rid of the MAGIC 100 */
答案 2 :(得分:-1)
Fread函数返回行读数而不是字符数确定? http://www.cplusplus.com/reference/clibrary/cstdio/fread/