文件例题(三)

本文介绍了一个简单的C语言程序,该程序从键盘接收输入的字符串,对其进行字母顺序排序,并将排序后的结果保存到磁盘文件中。此外,还提供了一个用于验证文件内容正确性的示例程序。

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

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 3
int 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 3
int 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;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值