我正在尝试编写一个程序来读取文件的现有记录,然后将它们索引到另一个文件中。记录存储在名为“players.bin”的文件中,该文件为 CSV 格式,每条记录包含(用户名、姓氏、名字、numwins、numlosses、numties,我想将它们索引到名为“players.idx”的新文件中。但是players.idx 文件将只包含一对序列,其中 username 是玩家的用户名,seq# 是玩家文件中存储的玩家记录的序列号。
这是我到目前为止的想法:
fd = open("players.bin", O_WRONLY | O_CREAT |
O_APPEND, S_IRWXU);
if (fd > 0) {
//Read the contents of the file (if any)
//and then print out each record until the end of file
while (num = read(fd, &plyr, sizeof (plyr)) != 0) {
printf("%s, %s, %s, %d, %d, %d\n\n", plyr.user_name,
plyr.last_name, plyr.first_name, plyr.num_wins,
plyr.num_losses, plyr.num_ties);
}
close(fd);
}
fd2 = open("players.idx", O_WRONLY | O_CREAT |
O_APPEND, S_IRWXU);
if (fd > 0) {
while (num = read(fd, &plyr, sizeof (plyr)) != 0) {
num = write(NOT SURE WHAT TO PUT HERE);
record_count++; //I am going to use this to keep track of seq numbers
}
close(fd2);
}
我真的很困惑如何去做......谢谢
最佳答案
找一本关于用 C 打开、读取和写入文件的书/教程。它相当简单,一旦您知道如何操作,只需打开一个文件进行读取,另一个文件进行写入即可。
很抱歉,我没有说得更具体,但要详细解释,我必须写一个冗长的答案,这仍然比阅读有关该主题的书或教程对您的帮助要小。
牢牢掌握之后,看看fscanf
和fprintf
,这两个函数将帮助您轻松解析和编写索引。
编辑:我真的建议不要跳过书/教程部分。您错误地打开了文件,我怀疑您也错误地读取了 .bin,尽管我必须查看您程序的其余部分才能确定。
关于C 程序 : How to read from one file and write into another? 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3955558/