查找并删除文件 C++ 中的整行

find and delete whole line in file c++

本文关键字:C++ 删除 文件 查找      更新时间:2023-10-16

我有一个文件,内容用';"分隔,像这样

JACK;Basketball;Afternoon
JACK;Football;Morning
JOE;Basketball;Morning
JIM;Football;Morning
KEN;Gym;Morning
MARK;Gym;Morning

所以我有这个代码

void deleteCourseData(string courserName, string courserType, string courseTime) {
ifstream myfile;
myfile.open("file.csv");
ofstream temp;
temp.open("temp.txt");
string line;
while (getline(myfile, line))
{
if(line.substr(0, courserName.size()) != courserName)
temp << line << endl;
}
myfile.close();
temp.close(); 
remove("file.csv");
rename("temp.txt", "file.csv");
}

此代码搜索课程名称并删除所有具有相同名称的数据。

因此,我想搜索所有数据"courserName,courserType,courseTime",然后删除该数据的整行。

您可以简单地将三个参数连接成一个字符串,并检查它,例如:

void deleteCourseData(string courserName, string courserType, string courseTime)
{
// additional scope introduced to control the lifetime of myfile and temp
{
ifstream myfile("file.csv");
ofstream temp("temp.txt");
string line;
string targetLine = courserName + ";" + courserType + ";" + courseTime;
while (getline(myfile, line))
{
if (line != targetLine)
temp << line << endl;
}
}
remove("file.csv");
rename("temp.txt", "file.csv");
}