Thread: erase a character from a file (something like backspace)

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    167

    erase a character from a file (something like backspace)

    I'm trying to find something of a backspace action to be done on files.
    Something like:
    - I for(i=0;i<n;i++) fprintf(file,"some text,\n");
    - and I want to erase the last 2 characters \n and , and replace them with . (like two backspaces and a . )

    I tried smthing like:
    Code:
    #include<stdio.h>
    
    int main()
    {
            printf("test.\n");
    
            printf("\b\b,\n");
    
            return 0;
    }
    from what I guess \b deletes the next two char (i want something to delete the previous)
    Last edited by spank; 08-27-2007 at 03:06 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Use fseek() to adjust the point you write to in a file.
    Though you need to be pretty careful when dealing with text files.
    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.

  3. #3
    Registered User
    Join Date
    Dec 2005
    Posts
    167
    I thought about that... but I hopped that there was something like a \b approach to it.

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    \b is a character just like any other, except the terminal interprets it differently.

  5. #5
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    You can only alter the values of bytes in-place. If you want to remove or insert bytes from a file, you have to either buffer a bunch of data in memory, or use a temporary file. Basic idea:

    Code:
    while not end of file:
        read bytes from input
        alter the bytes and write them to the output (a NEW file)
    end while
    
    copy temporary file back over the original file

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  3. Scope And Parameter Passing
    By djwicks in forum C Programming
    Replies: 6
    Last Post: 03-28-2005, 08:26 PM
  4. UNICODE and GET_STATE
    By Registered in forum C++ Programming
    Replies: 1
    Last Post: 07-15-2002, 03:23 PM