Thread: Overwriting a character

  1. #1
    Registered User
    Join Date
    May 2003
    Posts
    11

    Overwriting a character

    Using C, does anyone know how to overwrite a character in a file without copying the whole file to another new one?

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    11
    Does fprintf overwrite a string?

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>
    fopen() the file in "r+" mode
    fseek() to the char you want to overwrite
    <<
    You can't (or rather shouldn't) be fseek'ing on a non-binary stream, unless you are using the return value from a prior call to ftell() to determine the offset. If you do, you may run into trouble and start overwriting the wrong bytes in the file.

    So, the short answer is to use mode "r+b", but this will have an affect on any \n characters you output, and may cause trouble on Windows systems (due to CRLF end of line markers).
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  4. #4
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    You could read the entire file into a buffer (as text), modify the character(s) you want then save it again. This way you don't have to think of the fseek problem above.
    Not the best solution on big files though (the buffer consumes memory).
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. Character literals incorrectly interpreted
    By DL1 in forum C Programming
    Replies: 11
    Last Post: 04-05-2009, 05:35 PM
  3. <string> to LPCSTR? Also, character encoding: UNICODE vs ?
    By Kurisu33 in forum C++ Programming
    Replies: 7
    Last Post: 10-09-2006, 12:48 AM
  4. Character handling help
    By vandalay in forum C Programming
    Replies: 18
    Last Post: 03-29-2004, 05:32 PM
  5. UNICODE and GET_STATE
    By Registered in forum C++ Programming
    Replies: 1
    Last Post: 07-15-2002, 03:23 PM