[英]fread() binary mode not working properly in c++
我在用 c++ 編碼時遇到了fread()
函數的問題。 目標是以二進制模式打開文件進行寫入使用: fopen_s(&filename,filelocation,"wb");
, 使用fwrite(&buffer,size_of_read,count,filename)
精確地寫入一個字符串和一個 int,然后將數據讀回到其他變量中(請注意,在相同的程序,但這僅用於測試目的,因為我正在從事的項目嚴格基於加密,這是模塊之一)...
這是我的代碼:
int x = 1; // this is piece of data to write to the file
FILE *src; // the file variable that I am using
string text = "byebye"; // this happens to be the piece of data
src = fopen("F:\\_log.log", "wb"); // open file in binary write mode
fwrite(&text, 1, 7, src); // that's 7 because of 6 characters plus '\0'
fwrite(&x, 4, 1, src); // 4 bytes for int ---> writing x=1 to file
text.clear(); // for verification purpose
fclose(src);
src = fopen("F:\\_log.log", "rb");
int y = 0; // this is the int that will contain read data
string read; // string that contains read data
fread(&read, 1, 7, src); // read the data and store in read
fread(&y, 4, 1, src); // read the stored int into y
cout << "string is : " << read << "\nNumber is : " << y << endl;
上面程序的輸出對於整數似乎是正確的,但對於字符串卻不是......
string is :
Number is : 1
Number is : 1
語句清除首先y
為零,但文件中的數據已成功讀取並存儲在y
,然后變為1
但是,如果整數已被正確讀取,那么為什么不read
字符串另外, text
和read
似乎有同步,因為如果我更改命令text.clear();
到text="higuys";
那么輸出是:
string is : higuys
Number is : 1
我該如何解決這個問題? (完全無法理解該代碼中正在處理的內容......)
附加信息(雖然它可能沒有多大用處):
操作系統:Windows 10
IDE :代碼塊(也嘗試過 Visual Studio)
編譯器:GNU GCC
調試器:GDB
我嘗試使用perror();
來檢查任何錯誤perror();
和像cout<<fread(&read,1,7,src)<<endl;
這樣的技巧檢查讀取的字節數,但一切正常。 請幫我解決這個問題......
編輯 :
好的,我試過使用char
數組而不是string
,它奏效了!! 但是,有一件事尚不清楚,那就是:為什么兩個字符串text
和read
同步?
你需要改變
string read;
到
char read[7];
string 是一個類而不是一個緩沖區,所以你不能 fread 給出一個 string 對象的地址。
如果程序不僅適用於固定的 7 字節字符串,而且不僅適用於 C(您將問題標記為 C++),那么您應該考慮使用 ifstream/ofstream 和 string 並使用運算符 << 和 >> 寫入/讀取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.