Writing in file C++

2019-09-03 03:29发布

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.

标签: c++ file
3条回答
做自己的国王
2楼-- · 2019-09-03 04:09

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.

查看更多
Summer. ? 凉城
3楼-- · 2019-09-03 04:12

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

查看更多
贼婆χ
4楼-- · 2019-09-03 04:19

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");
}
查看更多
登录 后发表回答