c++ - 覆盖二进制文件中的字段

标签 c++

我正在编写一个程序,将结构写入二进制文件,然后为用户提供编辑文件的选项。然后程序应该重写文件中原始结构被写入的部分。代码:

struct Record
{
    char name     [16];
    char phoneNum [16];
    float balance;
};

int edit     ( fstream& ref)
{
    char searchVal[16];
    cout << "Enter customer name: ";
    cin.ignore();
    cin.getline(searchVal, sizeof(searchVal));
    int position = -1;
    Record buffer;
    bool found = false;

    while(!ref.eof() && !found)
    {
        position = ref.tellg();
        ref.read(reinterpret_cast<char*>(&buffer), RECORD_SIZE);
        if((strcmp(buffer.name,searchVal) == 0))
        {
            found = true;

            cout << buffer.name << " found! " << endl;

            cout << "Enter new customer name: ";
            cin.getline(buffer.name, sizeof(buffer.name));
            cout << "Enter new customer phone number: ";
            cin.getline(buffer.phoneNum, sizeof(buffer.phoneNum));
            cout << "Enter new customer balance: ";
            cin >> buffer.balance;

            ref.seekg(-(RECORD_SIZE), ios::cur);
            ref.write(reinterpret_cast<char*>(&buffer), RECORD_SIZE);

            position = ref.tellp();
            break;
        }
    }   
    if(!found)
    {
        cout << "Record not found" << endl;
    }

    ref.clear();
    ref.seekg(0L, ios::beg);
    return position;
}

基本上,找到了记录并且用户可以“编辑”它,但它写在文件的末尾,我不确定为什么。感谢您对此提供的帮助。

最佳答案

打开文件时不要使用模式ios::app。这种模式意味着输出应该附加到文件而不是覆盖。相反,使用 ios::ate,它告诉它在文件打开时寻找文件末尾,因此它不会被截断。

关于c++ - 覆盖二进制文件中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14805402/

相关文章:

java - IPC:为每个请求连接还是保持套接字打开?

php - 在 C++ 中使用 PayPal 自适应支付 API 的最佳方式是什么?

c++ - 为什么 injected-class-name 有时不被视为类模板中的模板名称?

c++ - 如果通过 QProcess 传递,则无法识别参数

c++ - 带有自定义比较器的 std::set_intersection

c++ - 从 Qt3 到 Qt4 : issues with internal classes ( Q3GList & Q3PtrCollection )

c++ - 用c++检查空格

c++ - 垂直方向的 Gtk3+ Spinbutton (c/c++)

c++ - 类型删除和分配器 : what's the expected behavior?

C++模板参数类型推断