将文本插入文本文件
好吧,这可能是最简单(或最愚蠢)的问题,但我刚刚知道......
假设我有一个包含帐号的文本文件。和平衡。我正在编写一个程序来使用输入的帐号搜索文件。并使用新余额更新同一文本文件中的余额字段。 我发现使用文件流来做到这一点非常困难。问题是我试图用新的 balance 字符串覆盖所述文本文件中的 balance 字符串。
因此,如果余额是 1000(4 位数字),我可以用另一个 4 位数字字符串覆盖它。但是,如果新的余额字符串超过 4 位,则会覆盖余额字段后的数据(请注意,这是一个简单的文本文件...)。 例如,如果文本文件包含
Acc. No. balance
123456 100
123567 2500
字段由制表符“\t”分隔,下一条记录由换行符“\n”分隔。如果我为帐户 123456 输入 200000 的新存款,fwrite() 函数将覆盖文本文件中的数据,如下所示...
Acc. No Balance
123456 2001003567 2500
您可以注意到余额字段后面的 '\n' 以及下一个帐户的 acc 中的 2 位数字。不。被覆盖。
当然,没有人希望这种情况发生:) 我需要的是一种在该文件中插入文本的方法,而不仅仅是覆盖它。使用 Java、Python 甚至 SED 执行此操作会产生很多结果,但使用 FILE 流却没有任何结果。 请分享您的想法...谢谢。
Alright, this maybe the simplest (or the stupidest) question, but I just got to know...
Suppose I have a text file containing account no. and balance. I am writing a program to search the file using entered account no. and update the balance field in the same text file with a new balance.
I am finding it surprisingly difficult to do so using file streams. The problem is that I am trying to overwrite the balance string in the said text file with a new balance string.
So, if the balance is 1000 (4 digits), I can overwrite it with another 4 digit string. But, if the new balance string is more than 4 digits, it is overwriting the data after the balance field (it is a simple text file mind you...).
For example, if the text file contains
Acc. No. balance
123456 100
123567 2500
The fields are separated by TAB '\t' character, and next record is separated by a newline '\n'. If I enter new deposit of 200000 for account 123456, the fwrite() function overwrites the data in the text file as...
Acc. No Balance
123456 2001003567 2500
You can notice that the '\n' after the balance field, and 2 digits from the next accounts' acc. no. is overwritten.
Of course, no-one wants that to happen :)
What I need is a way to insert text in that file, not just overwrite it. There are many results of doing this using Java, python or even SED, but nothing using FILE streams.
Please share your thoughts... thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须首先将插入点之后的所有数据向上移动几个字节。如果 Java、sed 或 python 一开始不编写临时文件,它们也会这样做。
You'll have to move all data after the insertion point a few bytes up first. That's what Java, sed or python do as well, if they aren't writing a temporary file to begin with.
如果您确实想在纯文本文件中管理数据:
在读入文件时,将数据的修改版本写入临时文件,然后删除原始文件并将临时文件重命名为原始文件名。但请注意,没有其他进程同时访问同一文件。
数据库系统就是为了这样的目的而发明的。因此,我建议在数据库表中管理数据,并在需要时动态创建文本报告。
If you really want to manage your data in a plain text file:
While you are reading the file in, write a modified version of your data into a temporary file, then delete the original file and rename the temp file to the original filename. But be carefull that no other process accesses the same file concurrently.
Database systems were invented for such purposes. So I recommend to manage your data in a database table and dynamically create a text report when needed.