我正在寻求有关如何使用C ++从txt文件中删除某些内容的帮助。 我知道如何打开一个txt文件并写入它,但我不知道如何删除文件中的某些内容。例如,用户打开文件,并想在文件中写“apple”,之后他们在文件中添加“banana”,然后希望删除“apple”。
答案 0 :(得分:2)
打开文件后,您可以继续一次读取其中的单词,然后一个简单的for
循环应搜索该单词并将其删除,您可以使用char变量word[20]
存储用户输入和另一个char array[]
来存储文件内容。要运行循环,可以使用int变量target_length
for(int i = 0; array[i] != '\0'; i++)
{
for(int j = 0; word[j] != '\0' && j < 20 ; j++)
{
if(array[i] != word[j])
{
break;
}
else
{
i++;
if(word[j+1] == '\0')
{
for(int k = (i-target_length); array[k] != '\0'; k++)
{
array[k] = array[k+target_length];
}
i = i - (target_length+1); // move the rest of the words one place left as words are deleted
}
}
}
}
答案 1 :(得分:1)
//My Assumption
//1.Comma use for seperation of string
#include <fstream>
#include <string>
#include <vector>
void main ()
{
//Writing data in file (comma use as seperator)
std::fstream fileStream;
std::string fileName = "TEXT.txt";
fileStream.open (fileName, std::fstream::in | std::fstream::out | std::fstream::app);
fileStream << "APPLE"<<","<<"BANANA";
fileStream.close();
//Remove all "APPLE" from file
std::ifstream readStream;
std::string lineData;
char * lineString;
std::vector<char*> fileData;
readStream.open(fileName);
if(readStream.is_open())
{
while(!readStream.eof())
{
std::getline (readStream,lineData);
if(!lineData.empty())
lineString = std::strtok(const_cast<char*>(lineData.c_str()),",");
int i= 0;
while (lineString!=nullptr)
{
if(strcmp(lineString,"APPLE")!=0)
{
fileData.push_back(lineString);
fileData.push_back(",");
}
lineString = std::strtok(NULL, ",");
}
}
}
readStream.close();
//Remove the original file
remove(fileName.c_str());
//Created a new file with same name
fileStream.open(fileName, std::fstream::in|std::fstream::out|std::fstream::app);
for(int i=0;i<fileData.size();i++)
fileStream<< fileData[i];
fileStream.close();
fileData.clear();
}
1) I insert data in text file using fstream.
2) I searches "APPLE" string in file.
3) I copied all content of file in vector except "APPLE" String.
4) I Remove original file.
5) I created new file with same name copied all vector data in file.