需要帮助关于通过fstream保存变量,我需要使用向量

Need help regarding saving variables via fstream, do I need to use vector?

本文关键字:向量 保存 帮助 于通过 fstream 变量      更新时间:2023-10-16

我做这个项目,我想为一个设备保存一些变量;

设备名称、ID和类型。
bool Enhedsliste::newDevice(string deviceName, string type)
{
fstream myFile;
string line;
char idDest[4];
myFile.open("Devices.txt", ios::app | ios::in | ios::out); //Opretter/Åbner fil, app = startlinje er den nederste linje, in out = input output
if (myFile.is_open())
{
    while (getline(myFile, line)) //Går filen igennem for hver linje
    {
        if (line == deviceName)
        {
            cout << deviceName << "-device already exists." << endl;
            return false;
        }
    }
}
else
{
    cout << "Uable to open file." << endl;
    return false;
}
myFile.close();
myFile.open("Devices.txt", ios::app | ios::in | ios::out); //Opretter/Åbner fil, app = startlinje er den nederste linje, in out = input output
if (myFile.is_open())
{
    if (type == "Lampe")
        type_ = 1;
    else if (type == "Roegalarm")
        type_ = 2;
    else if (type == "Tyverialarm")
        type_ = 3;
    else
    {
        cout << "Type does not exists." << endl;
        return false;
    }
    deviceName_ = deviceName;
    myFile << deviceName_ << endl;
    id_++;
    sprintf_s(idDest, "%03d", id_);
    myFile << idDest << endl;
    myFile << type_ << endl;
    myFile.close();
    return true;
}
else
{
    cout << "Uable to open file." << endl;
    return false;
}
}

现在我还想做一个deleteDevice,我可以把deviceName作为一个参数,它会找到那行并删除ID和类型,但我不知道如何做到这一点。

我需要重写我的addDevice向量吗?我该怎么做呢?

提前感谢,并为糟糕的代码,解释等道歉。我是新手。

要从当前文本文件中删除一行,您必须读取所有行,例如将数据存储在std::map中,删除相关项,然后再次将其全部写出来。另一种方法是使用数据库或二进制固定大小的记录文件,但将所有内容读入内存是常见的。顺便说一下,我将删除ios::app附加模式,以打开文件以供阅读。它翻译为相当于fopen的追加模式,但C99标准不清楚它对读取意味着什么,如果有的话。

要删除单个设备,您可以读取该文件并将其写入临时文件。传输/过滤数据后,重命名和删除文件:

#include <cstdio>
#include <fstream>
#include <iostream>
int main() {
    std::string remove_device = "Remove";
    std::ifstream in("Devices.txt");
    if( ! in) std::cerr << "Missing Filen";
    else {
        std::ofstream out("Devices.tmp");
        if( ! out) std::cerr << "Unable to create filen";
        else {
            std::string device;
            std::string id;
            std::string type;
            while(out && std::getline(in, device) && std::getline(in, id) && std::getline(in, type)) {
                if(device != remove_device) {
                    out << device << 'n' << id << 'n' << type << 'n';
                }
            }
            if( ! in.eof() || ! out) std::cerr << "Update failuren";
            else {
                in.close();
                out.close();
                if( ! (std::rename("Devices.txt", "Devices.old") == 0
                && std::rename("Devices.tmp", "Devices.txt") == 0
                && std::remove("Devices.old") == 0))
                    std::cerr << "Unable to rename/remove file`n";
            }
        }
    }
}