将数据重写到磁盘

时间:2015-02-20 18:27:42

标签: c++

我要求用户输入并将此数据写入磁盘。但是我希望用户能够更新这些数据。它将数据写入循环的第一遍。但是第二个循环没有更新描述。这是代码:

#include <iostream>

struct LabData {
    int recordNumber;
    char desc[16];
};

int main(int argc, const char * argv[]) {
    // insert code here...
    FILE *file = fopen("myfile.txt", "wb+");
    if(file == 0)
        std::cout << "ERROR FILE IS NULL!";

    for(int i = 0; i < 10; i++)
    {
        LabData lb;
        lb.recordNumber = i;
        std::cout << "Enter a description: ";
        std::cin.getline(lb.desc, 15);
        if(fwrite(&lb, sizeof(lb), 1, file) != 1)
            std::cout <<" ERROR IN WRITE!";
    }

    LabData lb;
    for(int i = 9; i >= 0; i--)
    {
        fseek(file, i * sizeof(LabData), SEEK_SET);
        fread(&lb, sizeof(LabData), 1, file);

        if(lb.recordNumber != i)
            std::cout << "Wrong record!";
        else
        {
            std::cout << "Record number: " << lb.recordNumber << " Description: " << lb.desc << std::endl;
            std::cout << "Enter new record description: ";
            std::cin.getline(lb.desc, 15);
            if(fwrite(&lb, sizeof(lb), 1, file) != 1)
                std::cout <<" ERROR IN WRITE!";
        }
    }

    for(int i = 0; i < 10; i++)
    {
        LabData lb;
        fseek(file, i * sizeof(LabData), SEEK_SET);
        fread(&lb, sizeof(LabData), 1, file);
        std::cout << "Record number: " << lb.recordNumber << " Description: " << lb.desc << std::endl;

    }

    fclose(file);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

在写入文件之前,需要先放fseek(file, i * sizeof(LabData), SEEK_SET);,在第二个循环中

std::cout << "Record number: " << lb.recordNumber << " Description: " << lb.desc << std::endl;
std::cout << "Enter new record description: ";
std::cin.getline(lb.desc, 15);
fseek(file, i * sizeof(LabData), SEEK_SET);
if(fwrite(&lb, sizeof(lb), 1, file) != 1)
    std::cout <<" ERROR IN WRITE!";

从文件中读取后,您必须回头重写相同位置的数据。