![](/img/trans.png)
[英]How can I use fread() on a binary file to read the data into a std::vector?
[英]How can I use fread to read in a file value by value?
我使用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
運行時,我得到了一個Segmentation錯誤。 當我用sudo ./a.out
運行它時,我沒有得到seg錯誤但沒有打印出來。 知道我能做些什么來解決它嗎?
我看到的問題:
分配比所需更多的內存
后
lSize = ftell (pFile);
lSize
設置為文件中的字符數,而不是unsigned short
s的數量。 因此,你需要
buffer = malloc(lSize);
請參閱我是否轉換了malloc的結果? 。 如果您使用的是C ++編譯器(正如您的C++
標記似乎暗示的那樣),則需要malloc
的返回值。
格式說明符錯誤
printf("%s\n", result);
使用錯誤的格式說明符來打印result
。 你需要使用
printf("%zu\n", result);
這條線是您看到的分割錯誤的最可能的罪魁禍首。
逐個閱讀對象
你當然可以使用:
size_t count = lSize/sizeof(short);
for ( size_t i = 0; i < count; ++i )
{
unsigned short number;
result = fread (&number, sizeof(unsigned short), 1, pFile);
}
您還可以使用:
size_t count = lSize/sizeof(short);
for ( size_t i = 0; i < count; ++i )
{
result = fread (buffer+i, sizeof(unsigned short), 1, pFile);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.