开发者

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

开发者 https://www.devze.com 2023-02-05 21:34 出处:网络
I have a text file. How do I go about delet开发者_JAVA技巧ing only the last line in the file using C?

I have a text file. How do I go about delet开发者_JAVA技巧ing only the last line in the file using C?

Thanks! John.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号