如何从C++中的文本文件中删除空行?

Zan*_*nix 2 c++

我一直在大学学习编程大约一年,我学习了一些东西,所以我决定制作我自己的"主编辑"程序,基本上编辑你的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;

}
Run Code Online (Sandbox Code Playgroud)

Pot*_*ter 5

由于您已将其标记为C++,因此我假设您要重写它以消除C FILE接口.

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';
    }
}
Run Code Online (Sandbox Code Playgroud)

http://ideone.com/ZibDT

非常直截了当!