【例10.3】从键盘输入若干个字符串,对它们按字母大小的顺序排序,然后把排好序的字符串送到磁盘文件中保存。
例10.3写入字符串并输出:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *fp;
char str[3][10],temp[10];
int i,j,k,n=3;
printf("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("C:\\Users\\yuhao2\\Desktop\\例10.3\\string.dat","w"))==NULL)
{
printf("can't open 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]);
}
return 0;
}
在VS2019下,需将源文件的gets、strcpy、fopen做些修改:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE* fp;
char str[3][10], temp[10];
int i, j, k, n = 3;
printf("Enter strings:\n");
for (i = 0; i < n; i++)
gets_s(str[i], 10);
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_s(temp, strlen(str[i]) + 1, str[i]);
strcpy_s(str[i], strlen(str[k]) + 1, str[k]);
strcpy_s(str[k], strlen(temp) + 1, temp);
}
}
fopen_s(&fp, "C:\\Users\\yuhao\\Desktop\\例10.3\\string.dat", "w");
if (fp == NULL)
{
printf("can't open 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]);
}
return 0;
}
例10.3读回字符串:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char str[3][10];
int i=0;
if((fp=fopen("C:\\Users\\yuhao2\\Desktop\\例10.3\\string.dat","r"))==NULL)
{
printf("can't open file!\n");
exit(0);
}
while(fgets(str[i],10,fp)!=NULL)
{
printf("%s",str[i]);
i++;
}
fclose(fp);
return 0;
}
在VS2019下,需将源文件的fopen做些修改:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE* fp;
char str[3][10];
int i = 0;
fopen_s(&fp,"C:\\Users\\yuhao2\\Desktop\\例10.3\\string.dat", "r");
if (fp== NULL)
{
printf("can't open file!\n");
exit(0);
}
while (fgets(str[i], 10, fp) != NULL)
{
printf("%s", str[i]);
i++;
}
fclose(fp);
return 0;
}