c++ - 使用 fstream 写入文件

标签 c++ stream fstream ostream

在类项目上工作,因此必须使用 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/

相关文章:

c++ - 为什么我的 fstream 访问不能编译?

stream - 停止/终止 WebRTC 媒体流

node.js - 如何使用 Gulp 在流中替换?

c++ - ifstream 和 ofstream : How do I perform multiple modifications to a file?

c++ - 在无序 map<string,vector<string>> 上使用 find() 与 C++ 中的有序 map 花费相同的时间

c++ - 如何使用 sprintf 将 uint_64 类型的数组附加到 char 数组?

c++ - 无法累积编译时间常量

3 向 header 中的 C++ 多重定义错误包括

stream - Common Lisp 与读字节/写字节的斗争

c++ - 将 fstream 数据写入磁盘时如何检测 fatal error ?