问题
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