如何用C替换txt文件中间的一行?
我正在从 txt 文件中读取信息(数字),然后将这些数字添加到另一个文件中的其他数字中,具有相同的结构。
文件中每一行的开头都有一个数字,用于标识特定产品。该代码将允许我在其他文件中搜索相同的产品。在我的程序中,我必须将一个文件中的其他“变量”添加到另一个文件中,然后在这些文件之一的同一位置替换它。
我没有使用 a
或 a+
打开任何这些文件,而是使用 r
和 r+
打开,因为我想替换可能位于文件中间而不是末尾的行中的信息。
该程序编译并运行,但是当涉及到替换文件中的信息时,它只是不执行任何操作。
我该如何解决这个问题?
I am reading info (numbers) from a txt file and after that I am adding to those numbers, others I had in another file, with the same structure.
At the start of each line in the file is a number, that identifies a specific product. That code will allow me to search for the same product in the other file. In my program I have to add the other "variables" from one file to the other, and then replace it, in the same place in one of those files.
I didn't open any of those files with a
or a+
, I did it with r
and r+
because i want to replace the information in the lines that may be in the middle of the file, and not in the end of it.
The program compiles, and runs, but when it comes to replace the info in the file, it just doesn't do anything.
How should I resolve the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
程序可以替换(覆盖)文件中间的文本。但问题是是否应该执行此操作。
为了插入更大的文本或更小的文本(并缩小间隙),必须写入一个新的文本文件。这是假设文件不是固定宽度的。基本规则是在插入新文件之前复制所有原始文本。写下新的文字。最后写剩下的原文。这是一项繁重的工作,甚至会减慢最简单的程序。
我建议您在继续之前设计您的数据布局。还可以考虑使用数据库,请参阅我的帖子: 什么时候值得使用数据库?
您的目标是设计数据以最大程度地减少重复和数据获取。
A program can replace (overwrite) text in the middle of the file. But the question is whether or not this should be performed.
In order to insert larger text or smaller text (and close up the gap), a new text file must be written. This is assuming the file is not fixed width. The fundamental rule is to copy all original text before the insertion to a new file. Write the new text. Finally write the remaining original text. This is a lot of work and will slow down even the simplest programs.
I suggest you design your data layout before you go any further. Also consider using a database, see my post: At what point is it worth using a database?
Your objective is to design the data to minimize duplication and data fetching.