newbie
newbie

Reputation: 4809

Writing in file C++

How can I write into a specific location of a file? My file contains the following info:

100 msc

I want to update it as:

100 10 20 34 32 43 44

So I want to skip 100 and overwrite msc with the new input array.

Upvotes: 0

Views: 238

Answers (3)

Loki Astari
Loki Astari

Reputation: 264749

First you have to understand that you can't modify files like that.
You can but its a little more tricky than that (as you need to have space).

So what you have to do is read the file and write it into a new file then re-name the file to the original.

Since you know exactly where to read to and what to insert do that first.

void copyFile(std::string const& filename)
{
    std::ifstream    input(filename.c_str());
    std::ofstream    output("/tmp/tmpname");


    // Read the 100 from the input stream
    int x;
    input >> x;


    // Write the alternative into the output.
    output <<"100 10 20 34 32 43 44 ";

    // Copies everything else from
    // input to the output.
    output << input.rdbuf();
}

int main()
{
    copyFile("Plop");
    rename("Plop", "/tmp/tmpname");
}

Upvotes: 1

Miguel
Miguel

Reputation: 1974

ktodisco's method works well, but another option would be to open the file with read/write permissions, and move the file position pointer to the write place in the buffer, and then just write what you need to. C++ probably has specifics to do this, but do it cleanly with just the C stdio library. Something like this:

#include <stdio.h>

int main() {
    FILE* f = fopen("myfile", "r+");
    /* skip ahead 4 characters from the beginning of file */
    fseek(f, 4, SEEK_SET);
    /* you could use fwrite, or whater works here... */
    fprintf(f, "Writing data here...");

    fclose(f);
    return 0;
}

You can use these as references: - fseek - fwrite

Hope I helped!

== EDIT ==

In C++ the iostream class seems to be able to do all of the above. See: iostream

Upvotes: 0

kevintodisco
kevintodisco

Reputation: 5191

The best way that I know of is to read in the complete contents of the file, and then use some string manipulations to overwrite what you need. Then you can write back the modified information to the same file, overwriting its contents.

Upvotes: 2

Related Questions