c++ - 如何从 C++ 中的文本文件中删除一个空行?

标签 c++

我已经在大学里学习编程大约一年了,一路上我学到了一些东西,所以我决定制作我自己的“Host editor”程序,它基本上可以编辑你的windows hosts 文件,允许您插入、删除和管理其中的 URL。 :)

但是,我在尝试从文件中删除 URL 时遇到了问题。我实际上并没有删除它,因为我不知道该怎么做,但我创建了一个新的空文本文件,然后复制除了带有我希望删除的 URL 的行之外的所有行。听起来很合理?

然而,似乎我无法删除 URL 而不离开所谓的“空行”。至少不是我的编码方式......我已经尝试了一切,我真的需要你的帮助。

但是请在这里和我一起使用“noob friendly”语言,我不会理解任何复杂的术语:)

谢谢,这是我的完整代码:

http://joggingbenefits.net/hcode.txt

这只是我认为困扰我的部分代码(删除 URL 功能):

void del(int lin)  // line index
{
    FILE* fp=fopen("C:\\Windows\\System32\\drivers\\etc\\hosts","r+");
    FILE* fp1=fopen("C:\\Windows\\System32\\drivers\\etc\\hosts1","w");

    char str[200];
    int cnt=0;

    while(! feof(fp))
    {
        fgets(str,200,fp);


        if(str[0]=='#')
        {
            fputs(str,fp1);
        }
        else
        {
            if(cnt==lin)
            {               // problem. FLAG?!
                cnt++;
            }
            else
            {
                    cnt++;
                    fputs(str,fp1);
            }

        }

    }



    fclose(fp);
    fclose(fp1);

    rename("C:\\Windows\\System32\\drivers\\etc\\hosts","C:\\Windows\\System32\\drivers\\etc\\deleteme");
    rename("C:\\Windows\\System32\\drivers\\etc\\hosts1","C:\\Windows\\System32\\drivers\\etc\\hosts");
    remove("C:\\Windows\\System32\\drivers\\etc\\deleteme");

    cout << endl << "LINE DELETED!" << endl;

}

最佳答案

由于您已将其标记为 C++,我假设您想要重写它以消除 C FILE 接口(interface)。

std::ifstream in_file("C:\\Windows\\System32\\drivers\\etc\\hosts");
std::ofstream out_file("C:\\Windows\\System32\\drivers\\etc\\hosts1");

std::string line;
while ( getline( in_file, line ) ) {
    if ( ! line.empty() ) {
        out_file << line << '\n';
    }
}

http://ideone.com/ZibDT

非常简单!

关于c++ - 如何从 C++ 中的文本文件中删除一个空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11794289/

相关文章:

c++ - 了解 `std::unordered_set`的用法

c++ - Lambda 隐式捕获因从结构化绑定(bind)声明的变量而失败

c++ - 访问 vector<vector<int>> 元素

c++ - 在没有 extern "C"的情况下在 C++ 中使用 dlsym

c++ - 字符串文字的本地化

c++ - Makefile:动态源文件名和对象目录

c++ - Rcpp - 将 sregex_token_iterator 的结果捕获到 vector

c++ - 指定初始值设定项中参数列表的大括号数量

C# ECDsaCng.SignData 在 OpenSSL 中使用签名?

c++ - 编译错误相关的 boost