81.调用函数,完成单向动态链表的建立,输出各结点的值.
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef struct lst 5 { 6 int num; 7 struct lst *next; 8 }LST; 9 10 LST *mycreat () 11 { 12 int m; 13 LST *head, *p, *q; 14 15 head = (LST *)malloc(sizeof(LST)); 16 q = head; 17 printf("建立链表,请输入数值: "); 18 printf("Input data: "); 19 scanf("%d", &m); 20 while (m != -1) 21 { 22 p = (LST *)malloc(sizeof(LST)); 23 q->next = p; 24 p->num = m; 25 q = p; 26 printf("Input data: "); 27 scanf("%d", &m); 28 } 29 q->next = NULL; 30 return head; 31 } 32 33 void myprint (LST *head) 34 { 35 LST *p; 36 p = head->next; 37 if (p == NULL) 38 printf("链表为空表! "); 39 else 40 do 41 { 42 printf("%5d", p->num); 43 p = p->next; 44 } while (p != NULL); 45 printf(" "); 46 } 47 48 void main (void) 49 { 50 LST *head; 51 head = mycreat(); 52 printf("新建链表为: "); 53 myprint(head); 54 }
结果:
建立链表,请输入数值:
Input data: 101
Input data: 103
Input data: 105
Input data: -1
新建链表为: 101 103 105
Mark:
"typedef struct lst LST;"表示可用LST代替struct lst;
82.编写程序将字符串"Let's study the C language."输出到一个文本文件.
1 #include <stdio.h> 2 3 void main (void) 4 { 5 char a[80] = "Let's study the C language."; 6 FILE *fp; 7 8 fp = fopen("a.txt", "w"); 9 fprintf(fp, "%s", a); 10 fclose(fp); 11 }
83.将以上文件"a.txt"中的内容读取出来,并输出到屏幕上.
1 #include <stdio.h> 2 3 void main (void) 4 { 5 char a[80]; 6 FILE *fp; 7 8 fp = fopen("a.txt", "w"); 9 fscanf(fp, "%s", a); 10 puts(a); 11 fclose(fp); 12 }
结果:
Let's
解释:
语句"fscanf(fp, “%s", a);"的作用是从文件指针fp所指文件"a.txt"中读取字符串,由于读字符串时,遇到空格,跳格符,回车符都认为字符串结束,因此输出结果是"Let's".若用fgets函数读入字符串,则输出结果将是"Let's study the C language.".
Mark:
"FILE *fp;"的作用是定义文件指针fp,在C程序中打开的所有文件都必须由文件指针指向后,才能作读取操作.
”fp = fopen("a.txt", "w");"的作用是用"写“的方式打开一个名为"a.txt"的文本文件,并将该文件与文件指针fp建立联系.
"fprintf(fp, ”%s", a);"的作用是将a中的字符串"Let's study the C language."输出到文件fp所指文件"a.txt"中.
语句"fclose(fp);"的作用是关闭fp所指文件"a.txt",这时文件与文件指针fp脱离联系.
84.从键盘输入若干学生的成绩,用-1结束,调用fprintf函数,按格式将学生的成绩写入文件d:cwz.txt中.
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 void main (void) 5 { 6 int a; 7 FILE *fp; 8 9 fp = fopen("d:\cwz\b.txt", "w"); 10 if (fp == NULL) 11 { 12 printf("Can't open file! "); 13 exit(0); 14 } 15 scanf("%d", &a); 16 while (a != -1) 17 { 18 fprintf(fp, "%4d", a); 19 scanf("%d", &a); 20 } 21 fclose(fp); 22 }
结果:
60 70 80 90 100 80 60 -1
程序运行后,屏幕上不显示任何信息,但在d盘cwz目录下找到b.txt文件,且文件的内容是:
60 70 80 90 100 80 60
如果在d盘下没有cwz目录,则文件打开失败,这时屏幕上显示信息:"Can't open file!",然后结束程序的执行.
85.调用fscanf函数,按格式读取以上文件d:cwz.txt中的学生成绩,并在中断屏幕上输出最高成绩.
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 void main (void) 5 { 6 int a, max = 0; 7 FILE *fp; 8 9 fp = fopen("d:\cwz\b.txt", "r"); 10 if (fp == NULL) 11 { 12 printf("Can't open file! "); 13 exit(0); 14 } 15 while (feof(fp) == 0) 16 { 17 fscanf(fp, "%d", &a); 18 printf("%4d", a); 19 if (max < a) 20 max = a; 21 } 22 printf(" "); 23 printf("max = %d ", max); 24 fclose(fp); 25 }
结果:
60 70 80 90 100 80 60
max = 100
函数feof用来判断文件是否结束,当数据读取到文件尾部时,feof(fp)的值为1,否则feof(fp)的值为0.