2017-01-03 122 views
0

我試圖創建一個包含數字的鏈表並將這些數字寫入一個文件,然後讀取相同的文件並讀取文件中的數據並打印這些數據數字。C:輸出錯誤鏈表和寫入和讀取文件

我該如何認爲問題是,讀取文件時出現錯誤。

我已經添加了用於調試的som打印語句,並且在打印正在寫入文件的內容時,它看起來沒問題。但是當我讀取文件並打印時,我得到用戶輸入的第一個數字打印兩次。 例如:

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

我真的不知道,如果有一個與我的鏈表問題,寫入文件,或者如果它是閱讀。所以,如果能夠幫助我更好地理解,我將不勝感激。

由於

#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-而-FEOF文件 - 總是錯的)。 –

+1

while(p-> tal!= 0)。你在哪裏定義了「tal」成員? –

+0

謝謝你們,所有的評論都有助於我們理解!feof的問題 – Taimour

回答

2

從的fread手冊(https://linux.die.net/man/3/fread):

的fread()和錯誤文件結束之間不區分,並且呼叫者必須使用FEOF(3)和ferror( 3)確定發生了什麼。

因此,您必須在打印p-> num之前檢查fread返回值。