클래스 프로젝트에서 작업하므로 fstream (입력/출력 모두), unique_ptr을 사용하고 고정 길이 직원 레코드를 쓰기위한 새 파일 만들기 (Employee의 EmployeeRec 구조체 사용) .fstream을 사용하여 파일에 쓰기
다음 작업을 수행 할 때 데이터가 실제로 쓰여지지 않습니다 ... 적어도 Visual Studio에서 스트림을 볼 때 스트림의 데이터를 표시하지 않으며 파일을 실제로 찾을 수 없습니다. 프로그램의 디렉토리. 컴파일은 잘되었지만 뭔가 빠져 있어야합니다. 어떤 아이디어?
적용 코드 : Employee.h에에서
: Employee.cpp에서
class Employee{
int id;
std::string name;
double salary;
struct EmployeeRec{ // Employee file for transfers
int id;
char name[31];
double salary;
};
void write(std::ostream&) const;
};
: 내 주요 드라이버에서
// Write an Employee record to file
void Employee::write(ostream& os) const{
EmployeeRec outbuf;
outbuf.id = id;
strncpy(outbuf.name, name.c_str(), 30)[30] = '\0';
outbuf.salary = salary;
os.write(reinterpret_cast<const char*>(&outbuf), sizeof outbuf);
}
:
// "employee.bin" does not exist prior
// EmpVect is a vector of unique_ptr<Employee> that has a few Employees already stored
fstream emprecs("employee.bin", ios::in | ios::out | ios::binary);
for (size_t i = 0; i < EmpVect.size(); ++i){
(EmpVect[i])->write(emprecs);
}
당신이 옳았습니다. 파일이 실제로 어떤 이유로 열리지 않았습니다. 이유는 모르겠지만, 명시 적으로 .open()을 호출하면 fstream에서이를 수정했습니다. 감사! – CGutz