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