从文件中删除一行 [英] Delete a single line from a file

查看:101
本文介绍了从文件中删除一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
请帮助我,我想通过显式指定行号从文件中删除特定行.
如果指定行号,则应从文件中删除相应的行.
你能让我知道我应该怎么做吗?

请帮助我.......

Hi all,
Please help me,I want to delete a particular line from a file by explicitly specifying the line number.
If I specify the line number, the corresponding line should be deleted from the file.
Can you please let me know how should I go about on this ?

Please help me.......

推荐答案

通过逐行递增计数器变量来读取文件行,并将该行写入临时输出文件,但当计数器变量具有您要删除的行号的值.从输入文件中读取所有行之后,关闭输入和输出文件.然后删除输入文件,并将临时输出文件重命名为原始文件的名称.

祝您编程愉快!

-MRB
Read the file line by line incrementing a counter variable and write that line to a temporary output file except for when the counter variable has the value of the line number you want to delete. After all lines have been read from the input file close input and output file. Then delete the input file and rename the temporary output file to the name of the original file.

Cheers and happy coding!

-MRB


您可以按照以下步骤进行操作.

*获取需要删除的行号.

*在读取模式下打开输入文件

*在写入/追加模式下打开一个临时文件,并将计数器变量设置为0

*从输入文件中逐行读取内容将计数器增加1

*如果计数器与输入行号匹配,则跳过该行以将其写入输出文件.

*继续直到文件结束.

*关闭两个文件.

*删除原始文件并将临时文件移动到原始文件.


这是您想要做的传统方式:)

BR//
Harsha
You can achieve this by following the steps below.

* Get the line number that needs to be deleted.

* Open the input file in Read Mode

* Open a temp file in write / append mode and set the counter variable to 0

* Read Contents from input file line by line Increment the counter by 1

* If the counter is matching with input line number then skip the line from writing into the output file.

* Continue untill end of file.

* Close both files.

* Remove the original file and move the temp file to original file.


This is the traditional way of doing what you want :)

BR//
Harsha


您应该逐行阅读文件(可以使用 getline [ ^ ]),并保存读取的行到内存缓冲区(例如,字符串向量(或到另一个临时文件)),跳过"要删除的"行.最后,使用内存缓冲区内容(或临时文件内容)覆盖现有文件.
You should read the file line by line (you may use getline[^] for the purpose), and save read lines to a memory buffer, for instance a vector of string (or to another, temporary, file), skipping the ''to be deleted'' line. Finally overwrite the existing file with the memory buffer content (or with the temporary file content).


这篇关于从文件中删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆