我用fwrite
來存儲一些數據,現在我試圖用fread
來讀取txt文件中的數據進行處理。我想單獨閱讀這些值,但我無法弄清楚如何做到這一點。這是我曾嘗試:如何使用fread按值讀取文件值?
#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
運行它時,我沒有收到seg錯誤,但沒有打印出來。 任何想法我可以做什麼來解決它?
做一些錯誤檢查這裏:'PFILE = fopen(「myfile.txt」,「rb」);' –
@πάνταῥεῖ什麼窩我檢查?這只是打開文件。只要我得到了正確的文件名,它應該可以正常工作。 –
你從來沒有根據'NULL'檢查返回值! –