0

I need to change the last character in large text files where the space between the end of the text and the EOF is padded with a handful of NULL characters. The problem is to find out where the text ends and the NULL padding begins.

I could read the file to a huge buffer and then check the length of the text with strlen() and then stet the write position according to the strlen() of the buffer. But, on a large file this is time consuming and costly in resources.

Is there any way of reading the file backwards, starting from the EOF (fseek(fp, 0L, SEEK_END)), one character at a time, until the first non-null character is encountered?

  • 1
    `NULL` is (a macro that expands to) a null *pointer* constant. Do you mean "null characters", i.e., bytes with the value `0x00`? – Keith Thompson Sep 19 '15 at 00:21
  • Reading it backwards could also be time-consuming if most of the file is nulls. So which one is better depends on whether there are more nulls at the end than characters at the beginning, and you can't know that unless you count one of them. – Barmar Sep 19 '15 at 00:30
  • Assuming unix-type environment, you can use mmap(2) to make the file look like a memory block, the decrement a pointer from the end while it points to NUL (not NULL) bytes. – mpez0 Sep 19 '15 at 00:40

0 Answers0