overwriting a specific line on a text file?

痞子三分冷 提交于 2020-01-10 20:09:09

问题


how do I go about overwriting a specific line on a text file in c?. I have values in multiple variables that need to be written onto the file.


回答1:


This only works when the new line has the same size as the old one:

  • Open the file in the mode a+
  • fseek() to the start of the file
  • Before reading the next line, use ftell() to note the start of the line
  • Read the line
  • If it's the line you want, fseek() again with the result from ftell() and use fwrite() to overwrite it.

If the length of the line changes, you must copy the file.




回答2:


Since files (from the point of view of C's standard library) are not line-oriented, but are just a sequence of characters (or bytes in binary mode), you can't expect to edit them at the line-level easily.

As Aaron described, you can of course replace the characters that make up the line if your replacement is the exact same character count.

You can also (perhaps) insert a shorter replacement by padding with whitespace at the end (before the line terminator). That's of course a bit crude.



来源:https://stackoverflow.com/questions/1832757/overwriting-a-specific-line-on-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!