次のコードを使用して、テキスト モードとバイナリ モードの 2 つのファイルを作成しました。
書き込み.cpp
struct person {
char name[20];
int age;
float weight;
};
int main(){
ofstream output("data.txt");
ofstream output2("data2.txt", ios::out|ios::binary);
int i;
person tmp;
for (i=0; i<4; i++){
cout<<"Write name: ";
cin >> tmp.name;
cout<<endl<<"age: ";
cin >> tmp.age;
cout<<endl<<"weight: ";
cin >> tmp.weight;
output.write((char*) &tmp, sizeof(tmp));
output2.write((char*) &tmp, sizeof(tmp));
}
output.close();
output2.close();
getchar();
return 0;
}
2つのファイルは同じです(16進エディタでもチェックしました)。
次のコードで読み取ろうとすると、最初の項目を読み取った後に EOF が返されます。
read.cpp
int main(){
bool found = false;
int pos;
person tmp;
ifstream file("data.txt");
if (!file) {
cout << "Error";
return 1;
}
while(!file.eof() && !found) {
file.read( (char*) &tmp, sizeof(tmp));
cout << "tmp.name: "<<tmp.name<<endl;
cout << "EOF? "<<file.eof()<<endl;
if (strcmp(tmp.name, "jack") == 0){
found = true;
//pos = file.tellg();
//pos -= (int) sizeof(tmp);
}
}
file.close();
cout << endl <<"Press ENTER to continue...";
getchar();
return 0;
}
出力
tmp.name: Jacob
EOF? 1
found? 0
しかし、ifstream をバイナリ モード ( ifstream file("data.txt", ios::in|ios::binary);
) で開くと、プログラムは検索対象の人を見つけます。ファイルをテキストモードで書いたのに、バイナリモードで動作する理由を誰かが説明してくれますか?