首页 > 解决方案 > 此代码编译正常但文件未创建?请指出错误

问题描述

我刚刚开始文件处理并开始编写代码以使用二进制文件创建、读取和写入,我将结构传递给它并尝试运行它,但我发现代码中指定的任何文件都没有在我的目录中创建虽然代码编译得很好。

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct Student
{
    char name[20];
    int student_id;
    char department[20];
    char address[30];
};
ostream & operator <<(ostream &out,Student &s1)
{
    out<<"Name: "<<s1.name<<endl;
    out<<"Student Id: "<<s1.student_id<<endl;
    out<<"Department: "<<s1.department<<endl;
    out<<"Address: "<<s1.address<<endl;
}
int main()
{
    Student s1;
    strcpy(s1.name, "Sandeep");
    s1.student_id = 1;
    strcpy(s1.department,"BCT");
    strcpy(s1.address, "New Baneshwor,Kathmandu");
    fstream file;  //file part
    file.open("Student.dat",ios::in | ios::out |ios::binary); //create a file
    file.write((char*)(&s1),sizeof(Student)); //write to it
    if(file.is_open())
    {
        cout<<"nice"; //check if it's open(code not running)
    }
    file.seekg(0);
    file.read((char*)(&s1),sizeof(Student)); //read from a file just created
    cout<<s1;
    if(file.fail())
    {
        cout<<"Cannot create file"; //check if file is not created
    }
    file.close();

}

标签: c++file-handling

解决方案


因为您使用ios::in | ios::out,所以该文件必须已经存在。你可以做:

file.open("Student.dat", ios::in | ios::out | ios::binary);
if ( !file.is_open() ) {
   file.clear();
   file.open("Student.dat", ios::out | ios::binary );
   file.close();
   file.open("Student.dat", ios::in | ios::out | ios::binary);
}

无耻地从这里偷走


推荐阅读