Q
写入文件C++
0
A
回答
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;
}
希望我帮助!
== ==编辑
在C++中iostream
类似乎能够做到以上所有。请参阅:iostream
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");
}
相关问题
- 1. C写()不写入文件
- 2. C++:写入文件
- 3. 写入文件 - C#
- 4. C++写入文件
- 5. 写入C文件
- 6. 写入文件c
- 7. 如何写入C#文件
- 8. C++:写入现有文件?
- 9. 无法写入文件c#
- 10. 用C写入CSV文件
- 11. 用c写入FIFO文件
- 12. 写入文件在c
- 13. C++ - 尝试写入文件
- 14. C#写入App.config文件
- 15. C#写入.resx文件
- 16. 部分写入文件 - C++
- 17. C#StreamWriter未写入文件
- 18. 写入resx文件c#
- 19. C#写入日志文件
- 20. C#写入excel文件
- 21. 写入文件 - 目标C
- 22. 如何写入文件C
- 23. C#写入文件问题
- 24. 读取文件并写入文件C
- 25. 使用c和C++写入文件
- 26. 写入/读取文本文件(C#)
- 27. C++写入文本文件损坏
- 28. 写入一个文本文件C#
- 29. C++多次将文本写入文件
- 30. 写入用户文档文件夹C++
如果您想要覆盖文件中的现有数据,则可以使用此功能。但是,如果要将新数据插入现有文件的中间,则必须使用ktodisco的方法。我无法分辨OP究竟在做什么,但看起来可能是后者。 – Sean 2012-02-05 01:49:32
@Sean我假设OP只是想覆盖它(因为他说:“我想跳过100,并用新的输入数组覆盖OVERWRITE”msc“)如果是另一种情况,那么是的,ktodisco的方法是可能最好。 – Miguel 2012-02-05 01:53:39
是的,但“msc”只有三个字符。如果他写得比那更多,那么他会写下在之后发生的事情。这就是为什么它看起来像我想插入,并需要先读取文件。 – Sean 2012-02-05 01:57:12