关于c语言读取文件信息到链表,怎么操作?

问题:在读取文件数据到链表时好像出错了,除了"w+"的打开方式会让打印函数在程序运行,其他的打开方式在程序运行后不显示。图片说明

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct stu {
    int id;
    int age;
    char name[10];
    int score;
    struct stu *next;
};
void printf_stu(struct stu * head)//打印函数
{
    struct stu *p = head;
    printf("学生成绩\n");
    printf("%-2s  %-2s\n", "学号", "成绩");
    while (p != NULL) {
        printf("%d   %d\n", p->id, p->score);
        p = p->next;
    }
}
struct stu * create(int n) {//输入链表函数
    int i;
    struct stu *head = NULL, *p, *q = NULL;
    for (i = 1; i <= n; i++) {
        if ((p = (struct stu *)malloc(sizeof(struct stu))) == NULL) {
            printf("不能分配!");
            exit(0);
        }
        p->next = NULL;
        printf("第%d个学生的信息:", i);
        scanf("%d%d", &p->id, &p->score);
        if (i == 1) head = p; else q->next = p;
        q = p;
    }
    return head;
}
void open_in(struct stu *head) {//输入文件函数1
    FILE *fp;
    struct stu *p = head;
    fp = fopen("c://学生信息表.txt", "w");
    fprintf(fp, "%s  %s\n", "学号", "成绩");
    while (p != NULL) {
        fprintf(fp, "%d  %d\n", p->id, p->score);
        p = p->next;
    }
    fclose(fp);
}
void open_inpp(struct stu *head) {//输入文件函数2
    FILE *fp;
    struct stu *p = head;
    fp = fopen("c://学生信息表.txt", "a+");
    fprintf(fp, "%s  %s\n", "学号", "成绩");
    while (p != NULL) {
        fprintf(fp, "4%d  4%d\n", p->id, p->score);
        p = p->next;
    }
    fclose(fp);
}
struct stu *createlink()//读取文件数据函数
{
    struct stu *head = (struct stu *)malloc(sizeof(struct stu));
    int t, y;
    struct stu *p;
    struct stu *q;
    FILE * fp;
    p = q = head;
    fp = fopen("c://学生信息表.txt", "r");
    while (fscanf(fp, "%d  %d\n", &t, &y) != EOF)
    {
        q = (struct stu*)malloc(sizeof(struct stu));
        q->id = t;
        q->score = y;
        p->next = q;
        p = q;
    }
    p->next = NULL;
    head = p;
    return head;
}
void main() {
    int n, i,sel;
    struct stu *head = NULL,*p;
    for (i = 1; i > 0; i++) {
        printf("1-输入学生数据   2-添加学生数据\n");
        printf("3-打印学生数据");
        printf("请输入选择(1-3)\n");
        scanf("%d", &sel);
        switch (sel) {
        case 3:
            head = createlink();
            printf_stu(head);
            break;
        case 2:
            open_inpp(head);
            break;
        case 1: printf("输入n:");
            scanf("%d", &n);
            head = create(n);
            open_in(head);
            break;
        }
        printf("1-回到上一页  2-结束\n");
        scanf("%d", &sel);
        if (sel > 1) break;
    }
    system("pause");
}

1个回答

fp = fopen("c://学生信息表.txt", "a+");
路径是反斜杠,不是除号斜杠

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐