簡體   English   中英

從C ++二進制文件讀取錯誤值

[英]fread from c++ binary file returning wrong value

我正在嘗試使用stdio.h將一些布爾網格寫入文件。 用戶輸入一個數字nx (通常為1到10),並且該程序通過ceil(nx / 2)布爾網格( ceil(nx / 2)ny )生成nx列表。 網格本身存儲在__int64 s中,因此此網格( f為false, T為true):

ffTT
fTfT

將是172(10101100)。

網格的最終列表輸出到二進制文件。

我的代碼:

std::vector<__int64> grids;

...

FILE *cFile;
if (fopen_s(&cFile, ("grid_" + std::to_string(nx) + "_c.bin").c_str(), "wb") != 0) return;

for (int i = 0; i < grids.size(); i++) {
    fwrite(&grids[i], (int) ceil((nx * ny) / 8), 1, cFile);
}

fclose(cFile);

這部分工作正常。


但是,當我嘗試從文件中讀取時,盡管大小正確,但所有網格的大小均為-858993460,盡管它能正確顯示網格數。 我的閱讀代碼:

FILE *cFile;
if (fopen_s(&cFile, ("grid_" + std::to_string(nx) + "_c.bin").c_str(), "rb") != 0) return;

fseek(cFile, 0, SEEK_END);
long size = ftell(cFile);

int grids = size / ((nx * ny) / 8);

for (int n = 0; n < shapes; n++) {
    __int64 data;
    fread(&data, (int) ceil((nx * ny) / 8), 1, cFile);
    printf("%i\n", data);
}

fclose(cFile);

我究竟做錯了什么?


如果您需要更多信息來回答,請發表評論,我會給您。

提前致謝!

問題

問題是您正在使用以下命令將FILE*移動到FILE*的末尾:

fseek(cFile, 0, SEEK_END);

然后,您嘗試讀取數據而不返回文件的開頭。

您不檢查以下內容的返回值:

fread(&data, (int) ceil((nx * ny) / 8), 1, cFile);

檢查讀取是否成功。

固定

添加行

fseek(cFile, 0, SEEK_SET);

倒帶文件。

始終檢查讀取操作的返回值。

if ( fread(&data, (int) ceil((nx * ny) / 8), 1, cFile) == 1 )
{
   // Successful read.
   // Use the data
}

我認為您以奇怪的方式使用fwritefread 請做

 fwrite(&gris[i], sizeof(__int64), 1, cFile);

用於轉儲和

 fread(&data, sizeof(__int64), 1, cFile);

恢復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM