在类项目上工作,因此必须使用 fstream(用于输入/输出)、unique_ptr,并创建新文件以将固定长度的员工记录写入(使用 Employee 中的 EmployeeRec 结构)。
当我执行以下操作时,数据实际上并没有被写入...至少在 Visual Studio 中查看时我没有在流中显示任何数据,并且我从未真正创建过我可以在程序的目录。编译得很好,但我一定遗漏了一些东西。有任何想法吗?
适用代码:
在 Employee.h 中:
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;
};
在 Employee.cpp 中:
// 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);
}
最佳答案
添加一些错误检查(ex is_open())来检查文件是否真的被打开了。有可能因为你没有权限等原因导致文件没有被创建。
您可以使用 strerror() 获取错误描述 http://www.cplusplus.com/reference/cstring/strerror/
另外,看看ofstream。 http://www.cplusplus.com/reference/ostream/ostream/?kw=ostream
关于c++ - 使用 fstream 写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22214861/