我正在做这个项目,我想为设备保存一些变量; Devicename,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重写为vector?我该怎么做?
提前致谢并对不良代码,解释等感到抱歉。我对此不熟悉。
答案 0 :(得分:0)
要从当前文本文件中删除一行,您必须阅读所有行,例如将数据存储在std::map
中,删除相关项目,然后再将其全部写回。另一种方法是使用数据库或二进制固定大小的记录文件,但将所有内容读入内存是很常见的。顺便说一句,我会删除ios::app
追加模式以打开文件进行阅读。它转换为fopen
的等效附加模式,但C99标准尚不清楚读取的含义,如果有的话。
答案 1 :(得分:0)
要删除单个设备,您可以读取该文件并写入临时文件。 传输/过滤数据后,重命名和删除文件:
#include <cstdio>
#include <fstream>
#include <iostream>
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";
}
}
}
}