文件例题(三)

来源:互联网 发布:latex windows 10 编辑:程序博客网 时间:2024/05/22 10:43

【题目】从键盘读入若干个字符串,对它们按字母大小的顺序排序,然后把排好序的字符串送到磁盘文件中保存。

#include<stdio.h>#include<stdlib.h>#include<string.h>#define N 3int main(){FILE *fp;char str[N][20],temp[20];int i,j,k;printf("Please enter strings:\n");for(i=0;i<N;i++)gets(str[i]);    for(i=0;i<N-1;i++){k=i;for(j=i+1;j<N;j++)if(strcmp(str[k],str[j])>0)k=j;if(k!=i){strcpy(temp,str[i]);            strcpy(str[i],str[k]);strcpy(str[k],temp);}}if((fp=fopen("D:\\ME\\C\\file1.dat","w"))==NULL) /* 在单引号或双引号中的'\'才需写成\\ */{printf("Cannot</A> open the file!\n");exit(0);}printf("\nThe new sequence:\n");for(i=0;i<N;i++){fputs(str[i],fp);fputs("\n",fp);printf("%s\n",str[i]);}fclose(fp);return 0;}

运行结果:

        为了验证输出到磁盘文件中的内容,可以编写如下程序:

#include<stdio.h>#include<stdlib.h>#define N 3int main(){FILE *fp;char str[N][20];if((fp=fopen("D:\\ME\\C\\file1.dat","r"))==NULL){printf("Cannot open the file!\n");exit(0);}int i=0;while(fgets(str[i],20,fp)!=NULL){printf("%s",str[i]);i++;}fclose(fp);return 0;}


 

 

原创粉丝点击