How to add one line before the last line in C
Hi I am working in C on Unix platform. Please tell me how to append one line before th开发者_如何学编程e last line in C. I have used fopen in appending mode but I cant add one line before the last line.
I just want to write to the second last line in the file.
You don't need to overwrite the whole file. You just have to:
- open your file in "rw" mode,
- read your file to find the last line: store its position (
ftell
/ftello
) in the file and its contents - go back to the beginning of the last line (
fseek
/fseeko
) - write whatever you want before the last line
- write the last line.
- close your file.
There is no way of doing this directly in standard C, mostly because few file systems support this operation. The easiest way round this is to read the file into an in memory structure (where you probably have it anyway), insert the line in memory, then write the whole structure out again, overwriting the original file.
Append only appends to the end, not in the middle.
You need to read in the entire file, and then write it out to a new file. You might have luck starting from the back, and finding the byte offset of the second-to-last linefeed. Then you can just block write the entire "prelude", add your new line, and then emit the remaining trailer.
You can find the place where the last line ends, read the last line into memory, seek back to the place, write the new line, and then the last line.
To find the place: Seek to the end, minus a buffer size. Read buffer, look for newline. If not found, seek backwards two buffer sizes, and try again.
You'll need to use the r+ mode for fopen
.
Oh, and you'll need to be careful about text and binary modes. You need to use binary mode, since with text mode you can't compute jump positions, you can only jump to locations you've gotten from ftell
. You can work around that by reading through the entire file, and calling ftell
at the beginning of each line. For large files, that is going to be slow.
Use fseek
to jump to end of file, read backwards until you encounter a newline. Then insert your line.
You might want to save the 'last line' you are reading by counting how many chars you are reading backwards then strncpy it to a properly allocated buffer.
精彩评论