不能将记录附加到二进制文件中
Cant append a record to a binary file
struct student
{
int identity;
char name[MAX];
int no_assessment;
char assessmenttask[MAX];
int mark;
};
void appendbfile(char filename [MAX])
{
ofstream writeb;
char filenameb [MAX];
strcpy(filenameb,filename);
student s;
strcat(filenameb,".dat");
cout<<"--------------------------------"
<<endl
<<"Begin appending for binary file "
<<filenameb
<<endl
<<endl;
cout<<"Enter student id: ";
cin>>s.identity;
cout<<"Enter student name: ";
cin>>s.name;
writeb.open(strcpy(filenameb,".dat"),ios::binary);
writeb.seekp(0,ios::end);
writeb.write (reinterpret_cast <const char *>(&s), sizeof (s));
writeb.close();
}
我可以运行程序,但我似乎不能附加一个记录到二进制文件。谁能帮我看一下?
谢谢
问题在下一行,您需要更改
writeb.open(strcpy(filenameb,".dat"),ios::binary);
writeb.open(filenameb, ios::binary);
因为你已经完成了strcat(filenameb,".dat");
,并且writeb.open
中的字符串将'.dat'复制到filenameb中,filenameb将文件名替换为'.dat'。如果你仔细看,文件'.dat'被创建在与你的程序相同的目录下,其中有你的数据。
也因为你不需要调用seekp(0,ios::end);
来移动文件指针到文件的末尾,本质上用ios::app
标志打开文件将追加文件到文件的末尾。
writeb.open(filenameb, ios::binary | ios::app);
writeb.write (reinterpret_cast <const char *>(&s), sizeof (s));
writeb.close();
查看文件打开模式:http://en.cppreference.com/w/cpp/io/ios_base/openmode
您需要将ios::app
标志传递给open函数:
writeb.open(filenameb, ios::binary | ios::app);
您还需要在open函数中使用ios::app or
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- 创建 Spdlog 异步文件记录器时遇到困难
- C++:实际上不是从二进制文件中读取
- 在二进制文件中删除记录
- 使用结构在二进制文件中创建多个记录
- 程序写入记录在 C++ 的二进制文件中两次
- 创建一个二进制文件,向其中添加信息,并从中读取所有记录(电话簿)
- 用c++更新二进制文件中的记录
- 如何使用seekg与字符串输入从二进制文件中获取记录
- 更新二进制文件中的学生记录,同时删除以前的数据
- 在二进制文件中添加特定的记录
- 不能将记录附加到二进制文件中
- 从二进制文件中删除记录