【发布时间】:2017-05-11 06:20:23
【问题描述】:
我使用fwrite 存储一些数据,现在我尝试使用fread 从txt 文件中读取数据进行处理。我想单独读取这些值,但我不知道你会怎么做。这是我尝试过的:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE * pFile;
long lSize;
unsigned short * buffer;
size_t result;
pFile = fopen ( "myfile.txt" , "rb" );
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (unsigned short *) malloc (sizeof(unsigned short)*lSize);
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
printf("%uz\n", result);
// terminate
fclose (pFile);
free (buffer);
return 0;
}
上面的程序编译得很好,但是当我用./a.out 运行它时,我得到一个分段错误。当我使用sudo ./a.out 运行它时,我没有遇到段错误,但没有打印出来。
知道我可以做些什么来解决它吗?
【问题讨论】:
-
在这里做一些错误检查:
pFile = fopen ( "myfile.txt" , "rb" ); -
@πάνταῥεῖ 我要检查什么?那只是打开文件。只要我的文件名正确,它应该可以正常工作。
-
你从来没有检查过
NULL的返回值! -
将结果打印为字符串 - 这可能是您的段错误的原因
-
@PiotrNycz 我更新了它,现在它只打印
524z。