c++ - 使用C++删除txt文件中的某些内容

标签 c++ file text-files

我正在寻求有关如何使用 C++ 从 txt 文件中删除某些内容的帮助。 我知道如何打开 txt 文件并写入它,但我不确定如何删除文件中的某些内容。例如,用户打开一个文件,想在文件中写入“apple”,后来在文件中添加“banana”,然后希望删除“apple”。

最佳答案

打开文件后,您可以一次继续读取其中的单词,一个简单的 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
            }
        }
    }
}

关于c++ - 使用C++删除txt文件中的某些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28212863/

相关文章:

c++ - 不同的答案 : two simple identical integer calculations?

c++ - 如何在 C++ 中使用 <threads> 和一维数组进行矩阵乘法?

android - 通过其键模式从android中删除上下文文件

c# - 从大文本文件中读取随机行

git - 为什么我的 .gitattributes 文件不能在我的 Mac 上运行?

c++ - 如何使用迭代器填充未知大小的 vector ?

c++ - 为 Windows cmd 添加 argc

c - 使用 fgets 从 .txt 文件读取并打印多行

c# - 在 C# 中创建文件的最快方法

scala - 如何原生地从Scala的HDFS中读取文本文件(不使用Spark)?