我使用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");
- πάντα ῥεῖ524z
。 - Fortuna Iwasaki