开发者

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.

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.

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜