2017-01-03 15 views
0

数字を含むリンクリストを作成し、それらの番号をファイルに書き込もうとした後、同じファイルを読み込み、数字。C:リンクされたリストとファイルへの書き込みと読み込み

何がだと思います。問題は、ファイルを読むときに問題があるということです。

私はデバッグのためにsomのprint文を追加しました。私がファイルに書き込んでいるものを印刷すると、okと思われます。しかし、私がファイルを読んでいるときに、ユーザーが最初に入力した番号が2回印刷されます。 例:

input: 1,2,3 
output:3,2,1,1 

ファイルへの書き込み、私のリンクリストに問題がある場合、私は本当に知らないか、それは読書だ場合。だから私はもっと理解してくれるどんなインプットもありがたいです。

おかげ

のfreadマニュアル( https://linux.die.net/man/3/fread)から
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 


typedef struct postTyp 
{ 
    int num; 
    struct postTyp *next; 
}postTyp; 

FILE *fp; 

int main() 
{ 
    postTyp *l, *p; //l=list , p=pointer 

    l = NULL; 
    p=malloc(sizeof(postTyp)); 


    //Creates linked list until user enters 0 
    printf("Enter a number, 0 to exit: "); 
    scanf("%i", &p->num); 

    while (p->num != 0) 
    { 
     p->next=l; 
     l=p; 
     p=malloc(sizeof(postTyp)); 
     printf("Enter a number, 0 to exit: "); 
     scanf("%i", &p->num); 

    } 
    free(p); 
    p=l; 

    //write the linked list to file 
    fp = fopen("test.txt", "w"); 
    while(p->next != NULL) 
    { 
     printf("%2i", p->num); 
     fwrite(p, 1, sizeof(postTyp), fp); 
     p=p->next; 
    } 
    printf("%2i", p->num); 
    fwrite(p, 1, sizeof(postTyp), fp); 
    fclose(fp); 

    printf("\n"); 

    //Code below to read the file content and print the numbers 
    fp = fopen("test.txt", "r"); 

    fread(p,sizeof(postTyp),1,fp); 
    fseek(fp,0,SEEK_SET); 

    //The first number entered at the beginning, will be printed twice here. 
    while(!feof(fp)) 
    { 
     fread(p,sizeof(postTyp),1,fp); 
     printf("-----\n"); 
     printf("%i\n", p->num); 
    } 

    fclose(fp); 


    return 0; 


} 
+3

ファイルを読み込んでいる間に何か間違っていることについてのあなたの考えは正しいです:「なぜwhile(!feof(file))」が常に間違っているのですか?](http://stackoverflow.com/questions/5431941/why -is-while-feof-file-always-wrong)を指定します。 –

+1

(p-> tal!= 0)である。どこに "tal"メンバーを定義しましたか? –

+0

ありがとうございました!問題を理解したら、すべてのコメントが役立ちました!feof – Taimour

答えて

2

のfread()end-of-fileとエラーを区別せず、発信者が((3)とferrorをfeofを使用する必要があります。 3)どのように発生したかを判断する。

したがって、p-> numを出力する前にfreadの戻り値をチェックする必要があります。

関連する問題