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)
{
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;
}
}
Now I also want to make a deleteDevice, where I can take deviceName as a parameter and it will find that line and delete ID and type, but I have no idea on how to do this.
Do I need to rewrite my addDevice to vector? And how do I do this?
Thanks in advance and sorry for bad code, explanation etc. I'm new to this.
To delete a line from your current text file, you will have to read in all lines, e.g. storing the data in a
std::map
, remove the relevant item, and write it all back out again. An alternative is to use a database or binary fixed size record file, but reading everything into memory is common. By the way, I would remove theios::app
append mode for opening the file for reading. It translates to the equivalent of append mode forfopen
, but the C99 standard is unclear on what it means for reading, if anything.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: