小写字母转成大写,并保存到文本文件中
#include<stdio.h>
int main()
{
FILE *fp;char ch;
if((fp=fopen("text.txt","w"))==NULL)
{
printf("cannot open!");
}
while((ch=getchar())!='0')
{
if(ch>='A'&&ch<='Z')
fprintf(fp,"%c",ch);
if(ch>='a'&&ch<='z')
fprintf(fp,"%c",(ch-32));
}
return 0;
}
读取文本文件中学生成绩,降序排列并5个一行存储//优化了一下冒泡排序,避免新增临时变量并与fptintf相结合
#include<stdio.h>
#define N 10
int main()
{
FILE *fp;int i,j,a[N];
if((fp=fopen("C:\\Users\\dell\\Desktop\\file.txt","r+"))==NULL)
{
printf("cannot open!");
}
for(i=0;i<N;i++)
{
fscanf(fp,"%d",&a[i]);
}
fprintf(fp,"\n------下面排序结果------\n");
for(i=N-1;i>=0;i--)
{
for(j=0;j<i;j++)
{
if(a[j]>a[j+1])
{
/*a[j]=a[j]+a[j+1];
a[j+1]=a[j]-a[j+1];
a[j]=a[j]-a[j+1];*/
a[j]=a[j]^a[j+1];
a[j+1]=a[j]^a[j+1];
a[j]=a[j]^a[j+1];
}
}
if((N-1-i)%5==0)
{
fprintf(fp,"\n");
}
fprintf(fp,"%d\t",a[i]);
}
fclose(fp);
return 0;
}
判断文件中的字母、数字、空格的个数
#include<stdio.h>
#define N 10
int main()
{
FILE *fp;char ch;int alphabet=0,num=0,space=0;
if((fp=fopen("C:\\Users\\dell\\Desktop\\file.txt","r"))==NULL)
{
printf("cannot open!");
}
while(!feof(fp))
{
ch=fgetc(fp);
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')) alphabet++;
if(ch>='0'&&ch<='9') num++;
if(ch==' ') space++;
}
fclose(fp);
printf("alphabet=%d\tnum=%d\tspace=%d",alphabet,num,space);
return 0;
}
输入员工工资信息并存储到文本文件
#include<stdio.h>
#define N 3
struct salary
{
char name[8];
char sex;
long sum;
}December[N];
int main()
{
FILE *fp;int i;
if((fp=fopen("C:\\Users\\dell\\Desktop\\file.txt","w"))==NULL)
{
printf("cannot open!");
}
fprintf(fp,"姓名\t性别\t工资\n");
for(i=0;i<N;i++)
{
scanf("%s %c %d",December[i].name,&December[i].sex,&December[i].sum);
fprintf(fp,"%s\t%c\t%d\n",December[i].name,December[i].sex,December[i].sum);
}
fclose(fp);
return 0;
}
/*姓名\t性别\t工资\n
王 m 6000
李 f 7000
张 f 8000
*/