[英]C program: How to read from one file and write into another? Indexing
I am trying to write a program that will read the existing records of a file and then index them in another file. 我正在尝试编写一个程序,该程序将读取文件的现有记录,然后将其索引到另一个文件中。 The records are stored in the file named "players.bin" which is CSV format each record contains (username,lastname,firstname,numwins,numlosses,numties and i want to index them in a new file named "players.idx". However the players.idx file will only contain a sequence of pairs of , where username is player's user name and seq# is the sequence number of the player's record stored in in the player file. 记录存储在名为“ players.bin”的文件中,该文件为CSV格式,每条记录包含(用户名,姓氏,名字,numwins,numlosses,numties,我想在名为“ players.idx”的新文件中为它们建立索引。 players.idx文件将只包含一对序列,其中username是玩家的用户名,seq#是存储在播放器文件中的玩家记录的序列号。
Here is what I have come up with so far: 到目前为止,这是我想出的:
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);
}
I am just really confused on how to go about this...Thanks 我真的很困惑如何去做...谢谢
Look for a book/tutorial on opening, reading and writing files in C. It's fairly easy, and once you know how to do it, it's just a matter of opening one file for reading, and another one for writing. 寻找有关使用C语言打开,读取和写入文件的书/教程。这很容易,一旦您知道该怎么做,打开一个文件进行读取,再打开一个文件进行写入即可。
I'm sorry I'm not more specific, but to explain in detail I'd have to write a loong answer that still would do you less good than reading a book on the subject, or a tutorial. 抱歉,我没有更具体,但是要详细解释,我不得不写一个简短的答案,仍然比阅读有关该主题的书或教程还差。
After you have a firm grip on that, take a look at fscanf
and fprintf
, those two functions will help you parse and write your index easily. 牢牢掌握这一点之后,看看fscanf
和fprintf
,这两个函数将帮助您轻松解析和编写索引。
edit : I really recommend not skipping the book/tutorial part. 编辑 :我真的建议不要跳过书/教程部分。 You're opening your files wrong, and I suspect you're reading the .bin erroneously too, though I'd have to see the rest of your program to be sure. 您打开的文件有误,我怀疑您也正在错误地阅读.bin,尽管我必须查看程序的其余部分以确保。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.