2012-02-05 112 views
0

如何写入文件的特定位置?我的文件包含以下信息:写入文件C++

100 msc 

我想更新为:

100 10 20 34 32 43 44 

所以我想跳过100,并与新的输入阵列覆盖msc

回答

2

我知道的最好方法是读取文件的完整内容,然后使用一些字符串操作来覆盖所需内容。然后,您可以将修改的信息写回到同一个文件,并覆盖其内容。

0

ktodisco的方法运行良好,但另一种选择是打开具有读/写权限的文件,并将文件位置指针移动到缓冲区中的写入位置,然后只写入所需内容。 C++可能具有这样的细节,但只需使用C stdio库即可完成。事情是这样的:

#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; 
} 

您可以使用这些作为参考: - fseek - fwrite

希望我帮助!

== ==编辑

在C++中iostream类似乎能够做到以上所有。请参阅:iostream

+0

如果您想要覆盖文件中的现有数据,则可以使用此功能。但是,如果要将新数据插入现有文件的中间,则必须使用ktodisco的方法。我无法分辨OP究竟在做什么,但看起来可能是后者。 – Sean 2012-02-05 01:49:32

+0

@Sean我假设OP只是想覆盖它(因为他说:“我想跳过100,并用新的输入数组覆盖OVERWRITE”msc“)如果是另一种情况,那么是的,ktodisco的方法是可能最好。 – Miguel 2012-02-05 01:53:39

+0

是的,但“msc”只有三个字符。如果他写得比那更多,那么他会写下在之后发生的事情。这就是为什么它看起来像我想插入,并需要先读取文件。 – Sean 2012-02-05 01:57:12

1

首先你必须明白,你不能修改那样的文件。
你可以但比它稍微棘手(因为你需要有空间)。

所以你需要做的是读取文件并将其写入一个新文件,然后重新命名文件到原来的文件。

既然你确切地知道在哪里阅读和插入什么做第一。

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