gpt4 book ai didi

c++ - 以下代码是单个文件中的文件读/写。但是此代码无法创建文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:48:54 26 4
gpt4 key购买 nike

我正在编写一个程序,用于读取和写入学生使用类(class)的记录。该程序不打开文件。所以我无法从文件中读取数据。

class Student
{
private:
unsigned roll ;
char name[30];
float perc;

public:
void getvalue()
{
cout<<"enter rollno , name and percentage :\n";
cin>>roll;
cin.ignore();
cin>>name>>perc;
}

void display()
{
cout << "\nRoll No : " << roll << "\nName : " << name
<< endl << "percentage : " << perc << endl;
}
};

int main()
{
char choice;
Student st ;
fstream file1;

file1.open("stud_rec1.bin", ios::binary|ios::in|ios::out );
do
{
cout<<"\n Detail of student :\n";
st.getvalue();

file1.write((char*)(&st) , sizeof(st));

cout<<"\nwant to input more record(y/n) : ";

cin>>choice;

} while(tolower(choice) == 'y');

file1.seekg(0,ios::beg);

while(file1.read((char*)(&st) , sizeof(st)) )
{
cout<<"1";
st.display();
}

file1.close();

getch();
}

最佳答案

当您调用 fstream::open() 并将模式设置为 ios::out|ios::in 时,只有当文件存在时才能打开该文件.如果文件不存在,fstream::open() 失败。参见 http://en.cppreference.com/w/cpp/io/basic_fstream/open和相关的http://en.cppreference.com/w/cpp/io/basic_filebuf/open .

改变

file1.open("stud_rec1.bin", ios::binary|ios::in|ios::out );

file1.open("stud_rec1.bin", ios::binary|ios::in|ios::out);
if ( !file1.is_open() )
{
file1.clear();
file1.open("stud_rec1.bin", ios::out); //Create file.
file1.close();
file1.open("stud_rec1.bin", ios::binary|ios::in|ios::out);

// If the file still cannot be opened, there may be permission
// issues on disk.
if ( !file1.is_open() )
{
std::cerr << "Unable to open file " << "stud_rec1.bin" << std::endl;
exit(1);
}
}

关于c++ - 以下代码是单个文件中的文件读/写。但是此代码无法创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32961750/

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