从文件读取数据到结构体中的C代码

5

我很久以来一直在苦苦挣扎,但是我无法弄清楚为什么它不起作用。

我正在尝试从文件中读取数字,这些数字的书写方式如下:

0 2012 1 1 2000.000000
0 2012 1 1 3000.000000
1 2012 1 1 4500.000000

我的结构:

struct element{

        int id;
        int sign;
        int year;
        int month;
        double amount;

        struct element *next;


};

struct queue{
    struct element *head;
    struct element *tail;
    struct element *head2; 
    struct element *temp;  
    struct element *temph; 

    int size;
};

(head2,temp和temph用于排序结构)并从文件中读取:
void read_str(struct queue *queue){

    FILE *reads;

    char filename[40];
    int temp;

    printf("Type in name of the file\n");
    scanf("%s",&filename);
    reads=fopen(filename, "r");
    if (reads==NULL) {
        perror("Error");
        return 1;
    }
    else { 
        while(!feof(reads)) {
            struct element *n= (struct element*)malloc(sizeof(struct element));             
            fscanf(reads,"%d %d %d %d %lf", n->id, n->sign, n->year, n->month, n->amount);                  
            n->next=NULL;                   

            if(queue->head ==NULL) {
                queue->head=n;
            }
            else {
                queue->tail->next=n;
            }

            queue->tail=n;
            queue->size++;                  

        }           
    }
}

我可以通过更改编写数据的函数来改变文件中数据的外观,但我不认为那是问题所在。我猜测我错误地使用了malloc

1个回答

21
fscanf(reads,"%d %d %d %d %lf", n->id, n->sign, n->year, n->month, n->amount);

scanf函数系列需要传递地址。将fscanf行更改为:

fscanf(reads,"%d %d %d %d %lf", &n->id, &n->sign, &n->year,
    &n->month, &n->amount);

顺便提一句,这句话非常误导:

else { while(!feof(reads)) {

谢谢,这很有帮助!为什么不应该使用 else { while(!feof(reads)) { - ozech
2
@ozech 晚了点回答,但你不应该使用feof(),因为它只在你尝试读取文件末尾之后才返回false。这可能会导致读入部分结构体,这可能不是你想要的。循环也可能会多执行一次。相反,你应该检查fscanf返回的值是否>= sizeof(your_struct)。这样你就知道已经读入了整个结构体。 - Alex Vallejo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接