覆盖文本文件上的特定行?
如何在 c 中覆盖文本文件上的特定行?我有多个变量的值需要写入文件中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅当新行与旧行大小相同时才有效:以
a+
模式打开文件fseek()
到文件开头ftell()
记下该行的开头ftell() 的结果再次使用
并使用fseek()
)fwrite()
覆盖它。如果行的长度发生变化,则必须复制该文件。
This only works when the new line has the same size as the old one:
a+
fseek()
to the start of the fileftell()
to note the start of the linefseek()
again with the result fromftell()
and usefwrite()
to overwrite it.If the length of the line changes, you must copy the file.
由于文件(从 C 标准库的角度来看)不是面向行的,而只是字符序列(或二进制模式下的字节),因此您不能指望轻松地在行级别编辑它们。
正如 Aaron 所描述的,如果您的替换字符数完全相同,您当然可以替换组成该行的字符。
您还可以(也许)通过在末尾(行终止符之前)填充空格来插入较短的替换。这当然有点粗糙。
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.