Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 二进制文件编辑_C++_File Io_Binary - Fatal编程技术网

C++ 二进制文件编辑

C++ 二进制文件编辑,c++,file-io,binary,C++,File Io,Binary,请帮助我在使用此功能时遇到问题。代码可以编译,但不会更改文件中的任何内容。我很困惑我该做什么。。。。我应该从文件中选择要编辑的记录,然后对其进行更改,我的当前代码允许我进行选择,但当我编辑记录时,不会存储任何内容 void editRecord(Cookie &type) { fstream dataFile; int num; int count = 0; dataFile.open("/Users/jordanmcpeek/Documents/201

请帮助我在使用此功能时遇到问题。代码可以编译,但不会更改文件中的任何内容。我很困惑我该做什么。。。。我应该从文件中选择要编辑的记录,然后对其进行更改,我的当前代码允许我进行选择,但当我编辑记录时,不会存储任何内容

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();

}
void editRecord(Cookie和类型)
{
流数据文件;
int-num;
整数计数=0;
打开(“/Users/jordanmpeek/Documents/2014_Summer/CSC_250/Unit_7/cookie.dat”,ios::in | ios::out | ios::binary);
read(reinterpret_cast(&type),sizeof(type));
//不在文件末尾时,显示记录
而(!dataFile.eof())
{
//显示记录。

您是否尝试在调试器中运行此操作?确保文件确实已成功打开?并且写入操作也已成功?您知道如何检查
fstream
操作是否失败吗?我知道文件已正确打开,因为我有其他可以工作的函数,如果您确实读取了文件的eof,则此函数会出现问题e将处于错误状态。在期望任何其他操作(如seek)成功之前,您需要清除错误。这就是为什么检查错误很重要的原因。在读取后放置一个数据文件。clear();解决了我的问题。感谢退休的忍者