문제

Working on a class project, so have to use fstream (for both input/output), unique_ptr, and create new file to write fixed-length employee records into (using the EmployeeRec struct in Employee).

The data is not actually being written when I do the following... at least I don't show any data in the stream when looking at it in Visual Studio and the file is never actually created that I can find in the program's directory. Compiles fine, but I must be missing something. Any ideas?

Applicable code:

In 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;
};

In 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);
}

In my main driver:

// "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);
}
도움이 되었습니까?

해결책

Add some error checking (ex is_open()) to check whether the file has actually been opened. It is possible that the file is not being created because you do not have permissions, etc.

You can get the error description using strerror() http://www.cplusplus.com/reference/cstring/strerror/

Also, have a look at ofstream. http://www.cplusplus.com/reference/ostream/ostream/?kw=ostream

다른 팁

Could it be because of the int member of EmployeeRec? You're reinterpret_casting a struct that has an int at offset 0 to a const char *. Depending on what your id actually is, and the endianness of your system, it is likely that the first byte of the EmployeeRec struct is a zero. You are then writing a null-terminated c-string whose very first byte is the null-terminator.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top