Synthetic Ascension
Synthetic Ascension

Reputation: 319

File Writing using fopen_s() & fseek() with SEEK_END

Situation

I'm trying to programatically write some code to a file to then be compiled. I need to be able to add code in without replacing the whole file. I have a } on the end of the file, which I need to remove to be able to add the next lot of code, after which the } is readded.

My code is currently thus:

    //Writes from an offset from the end of a file.
    static bool Write(const char *FilePath, const char *Text)
    {
        FILE *f;
        errno_t error;
        int seekerror;
        if (!(error = fopen_s(&f, FilePath, "w")))
        {
            //one byte offset from the end of the file.
            if (!(seekerror = fseek(f, -1, SEEK_END)))
            {
                fwrite(Text, sizeof(char), strlen(Text), f);
                fclose(f);
                return true;
            }
        }
        return false;
    }

Issue

I believe the w and a flags override the pointer location from fseek()? So I don't seem to be able to overwrite the } at the end of the file.

Does anyone know how I'd be able to write from an offset using SEEK_END?

Upvotes: 1

Views: 2008

Answers (1)

Phil Fighter
Phil Fighter

Reputation: 96

Don't use "w" mode for fopen, use "r+" instead.

"r" - Opens a file for reading. The file must exist.

"w" - Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.

"a" - Appends to a file. Writing operations, append data at the end of the file. The file is created if it does not exist.

"r+" - Opens a file to update both reading and writing. The file must exist.

"w+" - Creates an empty file for both reading and writing.

"a+" - Opens a file for reading and appending.

Upvotes: 2

Related Questions