Set a position in file stream to be EOF?

Discussion in 'C Programming' started by dacium, Jan 27, 2009.

  1. dacium

    dacium Guest

    Can you set the current position in a stream to be the new end of

    I am opening a file with fopen(filename,"r+b")

    I am moving back and forth with fseek to read and write in the file,
    but sometimes there is data at the end of the file that I don't want
    to be part of the file anymore. How do I truncate it?

    All I could find was ftrunctate but its unistd, so I am guessing there
    is no standard way accomplish a truncation?

    dacium, Jan 27, 2009
    1. Advertisements

  2. dacium

    dj3vande Guest

    A grep through n869 indicates that you are correct.
    (7.19.3#2 says "Binary files are not truncated, except as defined in"; lists the valid mode arguments for fopen, some
    of which cause truncation to zero-length, but I don't see any way to
    specify truncation at an arbitrary point in the file.)

    Writing a new copy of the file and then using remove() and rename() may
    be a suitable portable(-ish) way to accomplish this, but the behavior
    of remove() and rename() is specified weakly enough (and varies enough
    among popular platforms) that you're not losing a whole lot by just
    going straight to using POSIX system calls.

    If you have control over the file format, you may be able to avoid
    having to truncate by specifying some kind of padding that you can
    overwrite any leftover data with.


    Dave Vandervies dj3vande at eskimo dot com
    The UPS (basically a car battery with an IBM badge).
    --darwinist and Richard Heathfield in comp.programming
    dj3vande, Jan 27, 2009
    1. Advertisements

  3. dacium

    Eric Sosman Guest

    The Standard C library has no way to truncate a file; see
    Question 19.13 in the comp.lang.c Frequently Asked Questions
    (FAQ) list at <>. The FAQ's answer points
    out ftruncate(), chsize(), and fcntl() as possible "beyond C"

    Another possibility (FAQ Question 19.14) is to leave the
    file at its full size, but to write a recognizable "nothing to
    see here folks, just move along" pattern in the portion you'd
    like to "delete."
    Eric Sosman, Jan 27, 2009
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.