二进制文件 - 编辑

时间:2014-07-02 03:23:03

标签: c++ file-io binary

请帮助我解决此功能问题。代码编译和一切,但它不会更改文件中的任何内容。我很困惑我应该做什么....我应该从文件中选择一个记录进行编辑然后更改它,我当前的代码允许我选择,但是当我编辑记录时没有存储任何东西?

void editRecord(Cookie &type)
{
    fstream dataFile;
    int num;
    int count = 0;

    dataFile.open("/Users/jordanmcpeek/Documents/2014_Summer/CSC_250/Unit_7/cookie.dat", ios::in | ios::out | ios::binary);

    dataFile.read(reinterpret_cast<char *>(&type), sizeof(type));

    // While not at the end of the file, display the records
    while (!dataFile.eof())
    {
        // Display the records.
        cout << endl;
        cout << count << ". Description: ";
        cout << type.description << endl;
        cout << "Quantity Sold: ";
        cout << type.quantity << endl;
        cout << "Price: $";
        cout << type.price << endl;
        dataFile.read(reinterpret_cast<char *>(&type), sizeof(type));
        count++;
    }

    cout << "Which record would you like to edit?: ";
    cin >> num;
    cout << endl;
    cin.ignore();


    dataFile.seekp(num * sizeof(type), ios::beg);

    cout << "Please enter the new description for the cookie: ";
    cin.getline(type.description, SIZE);

    cout << endl;

    do
    {
        cout << endl;
        cout << "Please enter the new amount sold: ";
        cin >> type.quantity;
        cin.ignore();

    }while(type.quantity < 0);

    cout << endl;

    do
    {
        cout << "Please enter the new price: $";
        cin >> type.price;
        cin.ignore();

    }while(type.price < 0);

    cout << endl;

    // Change the record
    dataFile.write(reinterpret_cast<char *>(&type), sizeof(type));
    dataFile.close();

}

0 个答案:

没有答案