如何在C++中删除文本文件中的空行
How to delete an empty line from text file in C++?
我在大学里学习编程已经一年了,一路上我学到了一些东西,所以我决定制作自己的"主机编辑器"程序,它基本上编辑你的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
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何使用 c++ 实现并发文件/文本编辑?
- 我需要转换一些代码,以便它适用于输入和输出文件文本
- 通过套接字发送二进制文件.文本文件有效,其他文件无效
- 将大型数据文件拆分为多个小文件(文本格式)
- 如何读取输入文件(文本文件)并将输入验证为有效整数
- 从文本文件/文本流中读取Q字符串错误
- 从文本文件(文本解析器)C++中读取行和列的逻辑
- 如何将*.css文件(文本文件)的内容与附加信息存储在新文件中?
- 关于内存映射文件和使用大文件文本编辑器
- 如何在读取文件文本时跳过"n"
- 使用libzip从.zip获取文件(文本除外)