如何从c中的文件中删除最后几行(例如4行) [英] How to delete last few line ( e.g 4 lines) from a file in c

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

问题描述





我想写一个程序来删除文件中的最后几行。



我试过sed命令,但在我的运行时环境sed命令不起作用。



问候

Himanshu

Hi ,

I want to write a program to delete last few lines from a file .

I tried sed command , but on my run time environment sed command do not work.

Regards
Himanshu

推荐答案

我可以看到两种方法这样做

1)缓慢而基本的方式

您逐行读取文件,将最后4个读取保存在字符串数组中,然后在临时文件中打印最旧的文件。如果你有小文件,并希望最快的解决方案实现它钉它。

2)文件API方式

你打开文件, 寻找(使用fseek或OS提供的类似API)到文件末尾,向后扫描(按char更好地使用char),直到计算4个换行符,然后将文件大小设置为(通过打印EOF或通过API直接设置文件的大小。



由于这些解决方案非常依赖于平台并且对代码很简单,因此我谨慎地避免了代码片段并提供了onaly两种逻辑方法。

如果我的英语远非完美,我也很抱歉。希望有帮助。
I can see two ways of doing that
1) The slow and basic way
You read the file line by line, keep the last 4 read in a string array and then print the oldest one in a temp file. If you have small files and want the quickest solution to implement that nails it.
2) The file API way
You open the file, seek (using fseek or a similar API you OS provides) to the end of file, scan it backwards (works better char by char) until you count 4 newlines, then set the size of the file to that (by printing a EOF or setting directly the size of the file via API.

Since these solutions are very platform dependant and trivial to code I volountarily avoided code snippets and provided onaly two logical methods.
I also apologize if my English is far from perfect, I hope that helps.


读取并扫描文件并设置文件长度与 ftruncate
read and scan the the file and set the file length with ftruncate


这篇关于如何从c中的文件中删除最后几行(例如4行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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