Thread: Undoing fputc (removing a few bytes before end of file)?

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    30

    Undoing fputc (removing a few bytes before end of file)?

    Hi!

    I have been writing a binary file using the fputc function. Is there a function that offer a 'unfputc' ?

    This pseudo-code might help understand what I'm looking for:

    Code:
    #include <stdio.h>
    
    int main()
    {
        int i = 0; 
        FILE *fp;
        fp = fopen("teste", "w+b");
    
        for (i = 0; i < 10; i++)
       {
            fputc('t',fp);
            fputc('e',fp);
            fputc('s',fp);
            fputc('t',fp);
    
        }
    
        /*  Code here to remove the last 'test' entry (last 4 bytes of the file) */
    
        fclose(fp);
        return 0;
        
    }
    I know that I could use fseek(fp, -4, SEEK_CUR); to go 4 bytes back in the stream, however what I want is to actually strip the last 'x' bytes of a file. I know I could use a char* to do all operations and then write to a file, but I have already a large program that writes directly to the file, so I was wondering if there's a way to get around this.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    There's no standard way to do that.

    Some implementations have a truncate() function, but you'd have to read your local manual to find that out.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. algorithm for duplicate file checking help
    By geekoftheweek in forum C Programming
    Replies: 1
    Last Post: 04-04-2009, 01:46 PM
  2. Page File counter and Private Bytes Counter
    By George2 in forum Tech Board
    Replies: 0
    Last Post: 01-31-2008, 03:17 AM
  3. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM