-2
我有一個由fortran代碼創建的二進制文件。我想寫一個C++代碼來讀取這個二進制文件,然後通過std :: cout吐出來。這是到目前爲止我的代碼:簡單的C++二進制文件讀取
#include<fstream>
#include<iostream>
using namespace std;
int main(){
ifstream file("tofu.txt", ios::binary | ios::in | ios::ate);
ifstream::pos_type size;
if(file.is_open()){
size = file.tellg();
cout << "size = " << size << '\n';
file.seekg(0);
char bar[500];
file.read((char*) (&bar), size);
file.close();
string foo(bar);
cout << "foo = " << foo << '\n';
}
else cout << "Unable to open file";
return 0;
}
然而,編譯和運行時,該代碼給我什麼:
size = 250
foo =
有人能告訴我在哪裏,我做錯了的代碼?謝謝!
你的代碼是未定義行爲,因爲'bar'沒有內容形成以空字符結尾的字符串。 –
該文件包含什麼?例如,如果第一個字節爲零,則它工作得很好。 –
@KerrekSB:很好。 'char bar [500];'應該替換爲'char bar [500] = {0};' –