![](/img/trans.png)
[英]When is the file loaded into memory - for fread, fopen and fwrite calls?
[英]Having issues with fread and fwrite when writing some characters and a struct to a file and reading them back
我想寫一個文件的三個字符,然后是一個結構,然后再寫一個字符。 最后我想讀取struct之前的字符,struct本身,struct之后的字符並在屏幕上顯示它們。
struct stuff{
int a;
int b;
};
int main(){
FILE * fp = fopen("input.txt", "w+");
char charA = 'z';
char charB = 's';
char charC = 'q';
char charD = 'e';
//create a struct of type stuff
stuff s;
s.a = 123;
s.b = 2111;
//fwrite three first chars
fwrite(&charA, 1, sizeof(char), fp);
fwrite(&charB, 1, sizeof(char), fp);
fwrite(&charC, 1, sizeof(char), fp);
//fwrite the struct
fwrite(&s, 1, sizeof(struct stuff), fp);
//fwrite the last char
fwrite(&charD, 1, sizeof(char), fp);
//read the char before the struct, the struct itself,
// and the char after the struct
char expectedCharC;
stuff expectedStructS;
char expectedCharD;
fseek(fp, sizeof(struct stuff) + sizeof(char), SEEK_END);
fread(&expectedCharC, 1, sizeof(char), fp);
fread(&expectedStructS, 1, sizeof(struct stuff), fp);
fseek(fp, sizeof(char)*3 + sizeof(struct stuff), SEEK_SET);
fread(&expectedCharD, 1, sizeof(char), fp);
cout<<expectedCharC<<" "<<expectedStructS.a<<" ";
cout<<expectedStructS.b<<" "<<expectedCharD<<endl;
fclose(fp);
return 0;
}
而不是這個結果:
q 123 2111 e
我得到這個結果:
4197174 0 e
我不知道我做錯了什么。 我正在向文件寫入字節,將其讀回並在屏幕上顯示。 出了什么問題?
先感謝您
哇,你的代碼中有很多問題。 讓我們一個一個地解決它們。
正如unwind所提到的,你用來打開文件的模式似乎是不正確的。你正在嘗試做什么。 首先,您嘗試從僅為只寫的文件中讀取 。
你錯誤地使用了fwrite
。 它是fwrite(pointer to data, size of each data, number of data, FILE pointer);
。
你錯誤地使用了fseek
。 我看到你對offset
參數感到困惑。 此偏移量定義了從指定為fseek
的最后一個參數的origin
有符號距離 。 因此,如果您處於SEEK_END
,則應將您的offset
設為負數,從而向后移動。
我自己完成了這些更改,現在它可以工作了。 輸出: q 123 2111 e
這里也是一個不錯的小網站 。 幫助我解決你的問題。
謝謝你的閱讀。
首先,正如已經指出的那樣,您必須以二進制模式打開文件。 即使這樣,只是轉儲struct
的字節意味着將來某個時候你將無法正確讀取它。 但只要你從同一個過程中讀取,就應該沒問題。
真正的問題是你正在對所有的fseek
做什么:在第一個fread
之前,你做了一個超出文件末尾的fseek
。 任何從該位置的讀取都將保證失敗。 您真的應該檢查文件的狀態,並確保在訪問您讀取的任何值之前fread
已成功。 如果失敗,訪問變量(至少是那些stuff
)是未定義的行為; 最有可能的是,你會得到一些隨機垃圾。
你的第一個fseek
可能應該是文件的開頭,否則:
fseek( fp, -(sizeof( stuff ) + 4), SEEK_BEG);
如果你剛剛閱讀了結構,那么第二個fseek
也是不必要的。 (在您的情況下,這意味着正確讀取了最終的'e'
。)
您必須以二進制模式打開文件才能使其正常工作。
FILE * fp = fopen("input.txt", "wb+");
^
|
blam!
你想要的結果也有點不清楚,不應該從三個字符'z'
, 's'
和'q'
,然后有整數? 請注意,如果您使用的是小端機器,則整數可能會出現字節交換。
為了幫助調試代碼,您應該為所有I / O調用添加返回值檢查,因為I / O可能會失敗。 另請注意, sizeof (char)
始終為1
,因此編寫它並不是非常有益。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.