如何防止我的记录覆盖c++
how can i prevent my record from overwrite c++
如何防止我的记录覆盖c++
cin.get (terminator);
FILE * dat = fopen("Accounts.dat", "wb");
myAccount.username = myUsername;
myAccount.password = myPassword;
int n = 0;
int filenumber=0;
filenumber= n;
fseek(dat,sizeof(myAccount), ios_base :: end);
fwrite(&myAccount, sizeof(myAccount),ios_base ::app, dat);
fclose (dat);
一些理论:fseek
是stdio.h中的一个C例程(C++中的<cstdio>
)。它与以下中的C文件描述符一起工作
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ("myfile.txt","w");
if (pFile!=NULL)
{
fseek ( pFile , 0 , SEEK_SET );
fputs ("fopen example",pFile);
fclose (pFile);
}
return 0;
}
请注意与fseek
一起使用的SEEK_SET
标志。
ios_base::end
和类似的是与<fstream>
例程结合使用的C++成员常量,如下所示
#include <fstream> // std::fstream
int main () {
std::fstream fs;
fs.open ("test.txt", std::fstream::in | std::fstream::out | std::fstream::app);
fs << " more lorem ipsum";
fs.close();
return 0;
}
你应该NEVER在任何时候混合这些,它不是类型安全的,即使它有效,也不能保证它会有效,而且它不可移植,也是一种糟糕的代码实践。
从你的小片段中没有什么可以推断的,但如果你遇到了奇怪或错误的行为,你应该首先检查一下这些概念。
参考文献:http://www.cplusplus.com/reference/cstdio/fseek/http://www.cplusplus.com/reference/fstream/fstream/open/
请勿将FILE*
与std::fstream
混合使用。使用其中一个。
std::fstream File("Accounts.dat", std::ios::out | std::ios::binary | std::ios::app);
if (File.is_open())
{
File.write(reinterpret_cast<char*>(&myAccount), sizeof(myAccount));
File.close();
}
或者如果使用C:
FILE* file = fopen("meh.dat", "ab+");
if (file)
{
fwrite(&myAccount, sizeof(myAccount), 1, file);
fclose(file);
}
相关文章:
- 使用ios:ate写入到流会覆盖现有文件
- 我可以重新分配/覆盖std::字符串吗
- 叮叮当当在修复时插入多个"覆盖"说明符
- 谷歌模拟和覆盖关键字
- TMap::Emplace() 在应用现有密钥时会覆盖吗?
- 此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
- 使用子类覆盖基类中定义的函数
- 当覆盖存在时调用基本虚拟"binded to object"函数
- C++指针在 for 循环中被覆盖
- "main"函数堆栈中的对象在第一个任务运行时被覆盖 (FreeRTOS)
- 为什么我的全局 new() 覆盖被绕过了?
- 被覆盖的函数不会反映在基类中,这是正常行为吗?
- C++找出覆盖同一行的数组
- 专门化模板覆盖函数/避免对象切片
- 重写打印函数而不是覆盖基类
- C++中"覆盖功能的异常规范比基本版本更宽松"的奇怪错误
- 如何在 c++ 中覆盖相同的文本文件
- 覆盖应用程序的低级别键盘挂钩问题
- glBindTexture 是否覆盖活动纹理单元的内容
- "虚拟""覆盖"析构函数