gpt4 book ai didi

c++ - 此代码可以正常编译,但未创建文件?请指出错误

转载 作者:行者123 更新时间:2023-12-02 10:20:46 26 4
gpt4 key购买 nike

我只是开始文件处理,开始编写代码来创建,使用二进制文件进行读写,我将结构传递给它并尝试运行它,但是我发现未在目录中创建代码中指定的任何文件虽然代码编译良好。

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

无耻被盗 from here

关于c++ - 此代码可以正常编译,但未创建文件?请指出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60302518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com