关于c语言文件操作乱码的问题

这个是文本存放的内容

img

但是使用我写的函数将它全部输出时候却只显示了2个,有一个是乱码 如图:

img

这里是我写的将文本内容输出的代码:

void xianshi(){
    FILE *fp;
    struct all *p;
    p = (struct all*)malloc(sizeof (struct all));
    if((fp = fopen("quanbu.txt","r+")) == NULL){
        printf("can not open file!");
        exit(1);
    }
    while(fscanf(fp,"%s %s %s %d %d\n",p->category,p->number,p->bookname,&p->out,&p->noout) != EOF){
        p = (struct all*)malloc(sizeof (struct all));
        p->next = phead ->next;
        phead ->next = p;
    }
    phead = phead ->next;
    printf( "%s\t%s\t%s\t%s\t%s\n","图书类别","书号","书名","已借出数量","未借出数量");
    while(phead){
        printf("%s\t%s\t%s\t%d\t%d\n",phead->category,phead->number,phead->bookname,phead->out,phead->noout);
        phead = phead -> next;
    }
    fclose(fp);
    freed(p);
}

逻辑不对哦。你先申请了p空间。
进入while循环,将至赋给了p执行的空间。再给又申请了一块空间,之间那块你没有保存,所以内存泄露,数据丢了。(文件第一行数据没了)接下来把这个新节点挂到phead上,所以从第二个开始就正常了。
都最后一个,你空间申请了,挂到了链表上,但没有读到数据,所以就会输出乱码。(头插,第一个乱码)

将while循环内p=malloc那句变成第三步,就可以了。

    while (fscanf(fp, "%s %s %s %d %d\n", p->category, p->number, p->bookname, &p->out, &p->noout) != EOF) {
        p->next = phead->next;
        phead->next = p;
        p = (struct all*)malloc(sizeof(struct all));  
    }
   // free(p);最后一个p内没数据,可以释放掉,不释放也不会影响结果

可能是phead没有赋初始值的原因,稍微修改了一下,可以正常运行了。如下:



#include <stdio.h>
#include <stdlib.h>

struct all{
    char category[20];
    char number[20];
    char bookname[20];
    int out;
    int noout;
    struct all * next;
}; 

void xianshi(){
    FILE *fp;
    struct all *p;
    struct all * phead = (struct all*)malloc(sizeof (struct all));
    phead->next=NULL;
   
    if((fp = fopen("quanbu.txt","r+")) == NULL){
        printf("can not open file!");
        exit(1);
    }
    
      p = (struct all*)malloc(sizeof (struct all));
    while(    fscanf(fp,"%s%s%s%d%d ",p->category,p->number,p->bookname,&p->out,&p->noout)!=EOF){
        p->next = phead ->next;
        phead ->next = p;
        p = (struct all*)malloc(sizeof (struct all));
    }
    phead = phead ->next;
   
    printf( "%-10s %-5s %-5s %-10s %-s\n","图书类别","书号","书名","已借出数量","未借出数量");
    while(phead){
        printf("%-10s %-5s %-5s %-10d %-10d\n",phead->category,phead->number,phead->bookname,phead->out,phead->noout);
        phead = phead -> next;
    }
    fclose(fp);
    free(p);
}
 
int main(void){
    xianshi();
} 

img