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

How to delete an empty line from text file in C++?

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

我在大学里学习编程已经一年了,一路上我学到了一些东西,所以我决定制作自己的"主机编辑器"程序,它基本上编辑你的windows主机文件,让你插入、删除和管理里面的URL。:)

然而,我在尝试从文件中删除URL时遇到了问题。我实际上并没有删除它,因为我不知道如何删除它,但我创建了一个新的空文本文件,然后复制除了我想删除的URL之外的所有行。听起来合理吗?

然而,我似乎无法删除URL,而不在所谓的"空行"中留下。至少不是我的编码方式……我已经尝试了一切,我真的需要你的帮助。

但请在这里与我使用"noob友好"的语言,我不会理解任何复杂的术语:)

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

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++,我假设您想要重写它以消除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';
    }
}

http://ideone.com/ZibDT

非常直接!

您还没有说明这个代码是如何失败的(或者给我们举了一些文本作为例子),但我注意到您的循环有问题。"文件结尾"条件是由试图读取超过文件结尾的行为引起的,但在fgets之前执行测试(feof,因此在最后一行上操作两次:控制在读取最后一行后进入循环,尝试读取另一行,但失败,对仍处于str中的行执行操作,然后终止循环。

代替

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

尝试:

while(fgets(str,200,fp))
{
  ...

原因

fgets()函数读取包含行尾字符的行('n'),而puts()函数写入传递到行尾字符中的行。所以如果你读

this line

它被存储为

this linen

在CCD_ 10中。并作为写回文件

this linenn

看起来像这个

this line

文件中。

修复

  • 使用"n"
  • 在使用CCD_17之前,请删除fputs()中的尾部str