How to delete only the last line of a ASCII text file using C?

大憨熊 提交于 2019-12-08 09:48:07

问题


I have a text file. How do I go about deleting only the last line in the file using C?

Thanks! John.


回答1:


Plain ANSI C doesn't provide any standard way to decrease the size of a file - the only way to do this in standard C is to copy the entire file contents to a new file, except for the part you want to omit.

Alternatively, you can use OS-specific functions to truncate the file in-place. For example, POSIX provides the ftruncate() function, which shortens a file to a given length. You would search for the beginning of the last line, then truncate the file immediately before this (using lseek() to obtain the position).


The easiest alternative of all, if you have GNU head, is just to use that:

head -n -1 < file.original > file.new



回答2:


You are correct with the approach. Sacn for newlines, remember the last one and then use truncate or ftruncate. see also How to truncate a file in C? .

hth

Mario



来源:https://stackoverflow.com/questions/4743561/how-to-delete-only-the-last-line-of-a-ascii-text-file-using-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!