如何防止我的记录覆盖c++

how can i prevent my record from overwrite c++

本文关键字:覆盖 c++ 记录 我的 何防止      更新时间:2023-10-16

如何防止我的记录覆盖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);
}