更新二进制文件

时间:2014-08-17 14:54:37

标签: c++ binary

我有一个二进制文件employee.dat

记录结构:

struct employee{
    int employee_no;
    char surname[20],forename[20];
    char sex;
    float salary,bonus;
};

我想编写一个程序来更新(在输入员工编号时)员工工资,其中新工资将在7,500-250,000范围内。

任何人都可以帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

首先,写下以下内容:

#include <iostream> // for console I/O
#include <fstream>  // for reading binary files.
#include <cstdlib>

int main(void)
{
  return EXIT_SUCCESS;
}

这应该是你的基础。让它运作。

如果数据文件存在,您应该尝试一些简单的操作,例如打印员工姓名:

int main(void)
{
   employee e;
   std::ifstream  data_file(/* insert filename here */, ios::binary);
   if (!data_file)
   {
     std::cerr << "Error opening data file.\n";
     return EXIT_FAILURE;
   }
   // Read one record.
   data_file.read((char *) &e, sizeof(e));
   cout << "Read employee record for: "
        << e.forename
        << " "
        << e.surname
        << "\n";
   return EXIT_SUCCESS;
}

从这里,你可以采取几种发展途径:
1)一次读取一条记录,并测试员工ID或姓名 2)将一个或一组员工读入缓冲区,然后搜索缓冲区。

查找一些方法:seekgseekp,在读取和写入前打开文件write

如果这不具体,请发布一个更详细的问题,说明您尝试的问题。