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

后端 未结 2 1233
我在风中等你
我在风中等你 2021-01-25 22:08

I doing this project, where I want to save some variables for a device; Devicename, ID and type.

bool Enhedsliste::newDevice(string deviceName, string type)
{
fs         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-25 22:34

    To delete a single device you might read the file and write to a temporary file. After transferring/filtering the data, rename and delete files:

    #include 
    #include 
    #include 
    
    int main() {
        std::string remove_device = "Remove";
        std::ifstream in("Devices.txt");
        if( ! in) std::cerr << "Missing File\n";
        else {
            std::ofstream out("Devices.tmp");
            if( ! out) std::cerr << "Unable to create file\n";
            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 failure\n";
                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";
                }
            }
        }
    }
    

提交回复
热议问题