简体   繁体   English

用文件C ++编写

[英]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. 所以我想跳过100并用新的输入数组覆盖msc

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. 然后,您可以将修改后的信息写回到同一文件,覆盖其内容。

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");
}

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. ktodisco的方法效果很好,但是另一个选择是打开具有读/写权限的文件,然后将文件位置指针移到缓冲区中的写位置,然后只写所需的内容。 C++ probably has specifics to do this, but do it cleanly with just the C stdio library. C ++可能具有执行此操作的细节,但仅使用C stdio库即可完全做到这一点。 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 您可以将它们用作参考: -fseek - fwrite

Hope I helped! 希望我能帮上忙!

== EDIT == ==编辑==

In C++ the iostream class seems to be able to do all of the above. 在C ++中, iostream类似乎能够完成上述所有操作。 See: iostream 请参阅: iostream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM