0

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

Thanks! John.

John
  • 1
  • 1
  • 1
  • 4
    What have you tried? And/or what exactly is required for you to get full credit on your homework? – Daniel DiPaolo Jan 20 '11 at 04:55
  • 1
    I've tried seeking to the EOF and then traversing back the to the next new line char. And LOL @ your insinuation that this is HW. Thanks for your concern, but I'm not a student. I have to delete the last record of a text file as an export operation in Excel is adding a new line char to the end. – John Jan 20 '11 at 05:09

2 Answers2

6

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
caf
  • 233,326
  • 40
  • 323
  • 462
0

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

Community
  • 1
  • 1
Mario The Spoon
  • 4,799
  • 1
  • 24
  • 36