c++ - 此代码编译正常但文件未创建?请指出错误
问题描述
我刚刚开始文件处理并开始编写代码以使用二进制文件创建、读取和写入,我将结构传递给它并尝试运行它,但我发现代码中指定的任何文件都没有在我的目录中创建虽然代码编译得很好。
#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);
}
无耻地从这里偷走
推荐阅读
- ios - 使用打开按钮从试飞中打开应用程序时在启动时崩溃
- matlab - 如何在 MATLAB 中使用点生成圆顶
- amazon-web-services - AWS ECS 容量提供商
- c# - 将参数传递给 C# 中的 .cmd 文件
- spring - Spring @RequestBody 是如何工作的?以及@RequestBody 如何映射 json 来自定义对象?
- javascript - 如果在移动设备中打开菜单,如何停止正文滚动?
- java - Flink 原始和托管状态。什么时候使用它们?
- r - 用 ggplot 和 2 个过滤器叠加 2 个条形图
- c# - 如何为外出请求 ASP.net c# 添加动态标头?
- laravel - 使用 \Mail::send 不能设置标题