tags:

views:

124

answers:

5

Hi I am working in C on Unix platform. Please tell me how to append one line before the 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.

+2  A: 

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.

unwind
There is no need to write the whole file: you can write from the insertion point only.
mouviciel
+3  A: 

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.

anon
There is no need to write the whole file: you can write from the insertion point only.
mouviciel
In which case you have to find the insertion point. Note that I said "the easiest way" - there are of course many others.
anon
+1  A: 

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.

Lars Wirzenius
@Sachin - Nope. This isn't rentacoder, this is a help site. We will help you, but we won't write your homework (or job assignments) for you. If you're new to C, that's okay, but the "give me teh codez" attitude will get you nowhere on this site.
Chris Lutz
+5  A: 

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.
mouviciel
+1, beat me to it by a few seconds :-)
ammoQ
+1  A: 

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.

lorenzog