簡體   English   中英

C程序:如何從一個文件讀取並寫入另一個文件? 索引編制

[英]C program: How to read from one file and write into another? Indexing

我正在嘗試編寫一個程序,該程序將讀取文件的現有記錄,然后將其索引到另一個文件中。 記錄存儲在名為“ 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語言打開,讀取和寫入文件的書/教程。這很容易,一旦您知道該怎么做,打開一個文件進行讀取,再打開一個文件進行寫入即可。

抱歉,我沒有更具體,但是要詳細解釋,我不得不寫一個簡短的答案,仍然比閱讀有關該主題的書或教程還差。

牢牢掌握這一點之后,看看fscanffprintf ,這兩個函數將幫助您輕松解析和編寫索引。

編輯 :我真的建議不要跳過書/教程部分。 您打開的文件有誤,我懷疑您也正在錯誤地閱讀.bin,盡管我必須查看程序的其余部分以確保。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM