안녕하세요 저는 C++을 처음 사용하고 구조에서 이진 파일로 데이터를 쓰고 파일을 읽고 구조에 데이터를 다시 저장하려고합니다. 여기까지 내가 한 일은 다음과 같습니다.이진 파일에서 읽으면 액세스 위반이 발생합니다
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct Data{
string name;
int points[6];
};
int main(){
Data stream[20];
Data my[20];
for (int i = 0; i < 20; i++){
stream[i].name = "name" + to_string(i);
for (int j = 0; j < 6; j++)
{
stream[i].points[j] = j + i;
}
}
ofstream writer("data.dat", ios::binary | ios::trunc);
if (writer.is_open()){
writer.write((char *)stream, sizeof(stream));
writer.close();
}
else cout << "Error opening file.\n";
ifstream reader("data.dat", ios::binary);
if (reader.is_open()){
reader.read((char *)my, sizeof(my));
reader.close();
}
else cout << "Error opening file.\n";
for (int i = 0; i < 20; i++){
cout << my[i].name;
for (int j = 0; j < 6; j++)
{
cout << " " << my[i].points[j];
}
cout << endl;
}
system("pause");
return 0;
}
내가 컴파일하면 모든 것이 제대로 작동합니다. 데이터가 올바르게 표시되고 단추를 눌러 시스템 ("일시 중지") 붐 액세스 위반을 전달합니다. 내가 도대체 뭘 잘못하고있는 겁니까?
'sizeof (my)'는 무엇을 기대합니까? 'sizeof (my)'를 출력 할 때, 실제로 그것은 무엇입니까? http://stackoverflow.com/questions/3629301/c-sizeof – indiv
이진 파일에서 'std :: string'을 들락날락하게 만들 수는 없습니다. 이 파일을 작성하기 위해 네이티브 형식의 plain-old-data * 프로토콜을 만들어야합니다. – WhozCraig