此代码编译良好,但文件未创建?请指出错误

This code compiles fine but file is not created?Please point out the error

本文关键字:创建 错误 出错 文件 编译 代码      更新时间:2023-10-16

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

#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();
}

因为使用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);
}

无耻地从这里偷走