需要帮助关于通过fstream保存变量,我需要使用向量
Need help regarding saving variables via fstream, do I need to use vector?
我做这个项目,我想为一个设备保存一些变量;
设备名称、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";
}
}
}
}
相关文章:
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 如何在数组和向量 c++ 中存储和保存输入
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- C++ 将地址保存为字符串的向量转换为新的向量
- 使用 for 循环是否比在 C++ 中将内容保存在向量中更快?
- 将所有正则表达式匹配项保存在向量上
- 如何在向量中保存位置以供以后插入?
- 向量迭代器不兼容的错误,用于保存另一个向量的迭代器的向量
- 将局部变量保存到全局向量中,为什么离开局部范围后可以得到这些局部变量?
- 为什么可以访问在 for 循环中创建的向量,这些向量被保存到向量向量中
- 如何诊断保存和加载位向量(std::vector)的奇怪行为<bool>?
- 如何创建一个function_list<>类来保存具有相同模板语法的 std::function<>s 向量?
- 如何保存枚举类型的向量的向量
- 为什么我的将向量保存到文件然后再次读出的方法不起作用?
- 我可以将某些对象的指针保存在向量中,而不是将指针调用内联函数
- 分类一个向量,该向量由该类中的成员字符串保存对象
- 如何从二进制文件中读取双精度并将其保存在向量中
- C++将类对象的向量的向量保存到文件中
- 将对象向量保存到C++中的文件中
- 将字符串向量保存到磁盘不起作用