此代码编译良好,但文件未创建?请指出错误
This code compiles fine but file is not created?Please point out the error
我刚刚开始处理文件,并开始编写代码以使用二进制文件创建、读取和写入,我将结构传递给它并尝试运行它,但我发现代码中指定的任何文件都没有在我的目录中创建,尽管代码编译得很好。
#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);
}
无耻地从这里偷走
相关文章:
- C++使用params创建线程函数会导致转换错误
- 为什么加载SDF会导致Mobilizer创建闭环错误
- 此代码编译良好,但文件未创建?请指出错误
- 对象创建错误的C++矢量
- 如果用户输入的字符过多,则创建错误消息
- 本机库中的 OpenCV 创建错误
- #include "date.h" 创建错误 E1696 无法打开源文件"date.h",也无法打开包含文件:没有这样的文件或目录
- 使用makeword函数创建错误e0109-表观呼叫的括号前表达式必须具有(指针到 - )函数类型
- piThread在调用函数后创建错误
- CMAKE GCOV C 创建错误的.gcno文件
- 关于 C++ 中的头文件创建错误
- 窗口创建错误 - 可能是事件处理
- 氧气创建错误
- Xcode typedef 的 struct 创建错误/警告
- pthread 在分离的线程上创建错误 11
- 为什么代码创建错误的二进制搜索树
- 有人建议我的代码为什么在basic_ios和sstream中创建错误
- JNA -结构创建错误
- pthread在c++中创建错误
- 对象创建错误