|
|
发表于 2018-9-7 13:26:16
|
显示全部楼层
本帖最后由 claws0n 于 2018-9-7 13:29 编辑
写入- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct Student
- {
- char name[20];
- long long int numb;
- struct Student* pNext;
- } ;
- struct Student_1
- {
- char name[20];
- long long int numb;
- } ;
- struct Student * create()
- {
- FILE * fp;
- if((fp=fopen("student.txt","wb")) == NULL)
- {
- printf("cannot open file\n");
- exit(0);
- }
-
- struct Student *head, *pNew, *p;
- head->pNext = NULL;
- char ch;
-
- pNew = (struct Student*)malloc(sizeof(struct Student));
-
- p = head; //索引指针
- while( p->pNext ) //尾插法
- p = p->pNext;
- do
- {
- printf("请输入学生姓名:\n");
- scanf("%s", pNew->name);
- getchar();
- printf("请输入学生学号:\n");
- scanf("%lld", &pNew->numb);
- getchar();
-
- p->pNext = pNew;
- pNew->pNext = NULL;
- p = p->pNext;
-
- printf("是否继续录入(y/n):\n");
- ch = getchar();
- getchar();
- if(ch == 'y'|| ch == 'Y') //把大写也纳入
- pNew = (struct Student*)malloc(sizeof(struct Student));
-
- }while(ch == 'y'|| ch == 'Y'); //把大写也纳入
-
- p = head->pNext;
- while( p )
- {
- if(fwrite(p, sizeof(struct Student_1), 1, fp) != 1)
- {
- printf("录入出错!\n");
- }
- p = p->pNext;
- }
- fclose(fp);
- return head;
- }
- void print(struct Student* head)
- {
- struct Student *p;
- p = head->pNext;
- printf("姓名\t\t学号\n");
- while( p )
- {
- printf("%s\t\t%lld\n", p->name, p->numb);
- p = p->pNext;
- }
- }
- int main()
- {
- struct Student* head;
- head = create();
- system("cls");
- print(head);
- return 0;
- }
复制代码 读取- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct Student
- {
- char name[20];
- long long int numb;
- struct Student * pNext;
- } ;
- struct Student_1
- {
- char name[20];
- long long int numb;
- } ;
- struct Student * fprint()
- {
- FILE *fp;
- struct Student *head, *pNew, *p;
-
- if((fp = fopen("student.txt","rb")) == NULL)
- {
- printf("不能打开文件!");
- exit(0);
- }
-
- head->pNext = NULL;
- p = head;
-
- while(!feof(fp))
- {
- pNew = (struct Student*)malloc(sizeof(struct Student));
- fread(pNew, sizeof(struct Student_1), 1, fp);
-
- p->pNext = pNew;
- pNew->pNext = NULL;
- p = p->pNext;
- }
- return head;
- }
- void print(struct Student* head)
- {
- struct Student *p;
- p = head->pNext;
- printf("姓名\t\t学号\n");
- while( p->pNext )
- {
- printf("%s\t\t%lld\n", p->name, p->numb);
- p = p->pNext;
- }
- }
- int main()
- {
- struct Student* head;
- head = fprint();
- printf("reading...\n");
- print(head);
- return 0;
- }
复制代码
*head = NULL 的问题吧?虽然浪费了一个空间,但这样写不是更好吗? |
|