发出使用fstream写入文件的问题

时间:2014-03-06 04:20:47

标签: 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);
}

2 个答案:

答案 0 :(得分:0)

添加一些错误检查(ex is_open())以检查文件是否实际已被打开。由于您没有权限等,可能没有创建该文件。

您可以使用strerror()获取错误说明 http://www.cplusplus.com/reference/cstring/strerror/

另外,请看一下ofstream。 http://www.cplusplus.com/reference/ostream/ostream/?kw=ostream

答案 1 :(得分:0)

可能是因为EmployeeRec的int成员吗? 你重新解释了一个结构,它在偏移0处有一个int到一个const char *。根据您的id实际是什么以及系统的字节顺序,EmployeeRec结构的第一个字节很可能是零。然后编写一个以null结尾的c字符串,其第一个字节是空终止符。