下面的代码是在单个文件中读取/写入文件.但是这段代码不能创建文件
This following code is file read/write in a single file. but this code is not able to create file
我正在写一个程序,读取和写入学生使用类的记录。这个程序不能打开文件。所以我不能从文件中读取数据。
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++代码中包含opencv时,使用ctypes创建.so文件
- 此代码编译良好,但文件未创建?请指出错误
- 找不到Linux Visual Studio代码C++文件
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 如何使代码打印文本文件中的第一行?
- 编译多个C++文件.调用二进制文件以运行代码
- VI工作室代码错误无法打开输出文件主.exe
- 获取 clang++:错误:在编译文件系统库的代码时
- 如何在软件代码中使用ofstream创建文件
- 我可以删除 *.o文件(代码:: blocks)
- 用于人脸检测的Haar级联xml文件代码解释OpenCV
- 如何直接从分配的内存中执行mmaped二进制文件/代码
- 文件 I/O 代码未正确读取C++
- 单个文件代码中未定义的引用错误
- 将数组写入文件代码不起作用(C++)
- IO文件代码不一致
- 如何在单个文件C++代码中使用库
- 是否有可能改变.so文件代码在android工作室本身,并使构建
- 疑难解答阅读CSV文件代码
- Bazel头文件代码生成器