Thread: WriteFile and fwrite

  1. #1
    Registered User
    Join Date
    May 2006

    WriteFile and fwrite

    Hello everyone,

    I think there is a in-place re-write function which WriteFile supports, but fwrite does not support.

    Suppose I have a file, and the content is "foo is content", I want to change the content of the file to "goo is content".

    If I am using WriteFile API and open with CreateFile API (generic read | write, and open existing option), I can only write one byte 'g' to replace content in-place.

    But when using fwrite, there is no in-place re-write function, and I have to use "a+" mode to open a file and re-write all content "goo is content". Right?

    Are there similar functions in fwrite providing in-place re-write function?

    thanks in advance,

  2. #2
    Join Date
    Aug 2002
    Tucson, Arizona

  3. #3
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Umeň, Sweden
    Aren't you thinking of "w"? And have you tried?
    To my experience writing to a file not being at EOF replaces characters.
    I don't know what the standards has to say about it though.

  4. #4
    Day Dreamer
    Join Date
    Apr 2007
    yes that is correct, writing to a File before reaching EOF will replace characters in "w" mode.
    The OP can use fseek as right pointed out by prog-bman!

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    To summarize: No, you don't have to rewrite the entire content. If you open the file in "a+" or "r+" mode, the file content is preserved, and you can use fseek to find any particular position in the file (either as a direct number of bytes from start, relative to the current position or relative the the end of the file [the latter is quite useful if you want to ADD something to the end of the file after having overwritten something in the beginning or middle of the file]).

    fwrite willl just write the number of bytes you wish to write, where the current file-pointer is. The different modes of open decides whether the file is "emptied"(w) or "kept as is"(a) - and with a "+" added, it will allow both read and write. The difference between "w+", "r+" and "a+" is in the handling of the content of the file and whether the file needs to exist before you call fopen(). I believe "r+" means that writes happen at the start of the file, rather than at the end, if you don't use "fseek" to set the position.


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fwrite problem
    By recluse in forum C Programming
    Replies: 5
    Last Post: 05-02-2005, 10:00 AM
Website Security Test