C 程序:如何正确使用 lseek() 或 fseek() 修改文件的某一部分?
我有一个 CSV 格式的二进制文件,其中包含多个记录。每条记录均以 user_name、last_name、first_name、num_wins、num_losses、num_ties 形式输入。我正在创建一种方法来更新某个玩家的胜利、失败和平局记录。用户输入要更改的用户名,然后更改获胜、失败和平局。例如 smithj 4 5 1。这将找到 smithj 记录并将 4 添加到获胜等。
如何使用 lseek 或 fseek 来完成此操作?或者还有其他方法可以做到这一点吗?
I have a binary file in CSV format that contains multiple records. Each record is entered in as user_name, last_name, first_name, num_wins, num_losses, num_ties. I am creating a method to update a certain players record of wins,losses and ties. The user inputs the username to change followed by the changes to the wins, losses and ties. For example smithj 4 5 1. This will find the smithj record and add 4 to the wins etc.
How do I use lseek or fseek to accomplish this? Or is there another way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对示例写入请求的响应 - 假设固定大小的记录:
对于必须修改的每个记录,重复从
recnum
声明到末尾的代码一次(思考循环)。对于在编辑时改变大小的可变大小记录,您必须更加努力地工作 - 如此之多,以至于一次将旧文件复制到内存中一个记录,适当地修改记录,然后写入可能更简单修改记录到新文件。
Response to request for write-up of example - assuming fixed size records:
Repeat the code from the declaration of
recnum
to the end once for each record that must be modified (think loop).With variable size records that change size as you edit them, you have to work a lot harder - so much so that it is probably simpler to copy the old file into memory one record at a time, modifying the record appropriately, and then writing the modified record to a new file.
假设该文件是文本文件,那么您必须将行填充到恒定宽度。然后使用 lseek()、read() 和 write() 修改这些行。每行的长度恒定至关重要:它允许您计算每行的起始位置。
Assuming the file is a text file, then you will have to pad the lines to a constant width. Then use lseek(), read(), and write() to modify the lines. Having a constant length for each line is crucial: it allows you to compute the starting position of each line.
如果每个记录的字节数相同,则很容易做到。
您将检查第一条记录是否匹配,如果不匹配,则执行
fseek(f, record_size, SEEK_CUR);
并检查下一条记录。如果每个记录的字节数不同,我能想到的就是将记录的字节数放在实际记录之前。然后读入,然后 fseek() 那么多字节以获得下一个记录大小。我见过一些二进制文件格式可以做到这一点,这使得事情变得相当简单。
It's fairly easy to do if each record is the same number of bytes.
You would check the first record to see if it's a match, and if not then do
fseek(f, record_size, SEEK_CUR);
and check the next record.If each record is going to be a different number of bytes, all I can think of is that you put the number of bytes the record is before the actual record. And then read that in, and then fseek() that many bytes to get to the next record size. I've seen some binary file formats do this which makes things fairly easy.