首页 > 技术文章 > 文件操作-改

chenlong991223 2018-12-27 19:48 原文

程序一

用记事本建立文件src.dat,其中存放若干字符。编写程序,从文件src.dat中读取数据,统计其中的大写字母、小写字母、数字、其它字符的个数,并将这些数据写入到文件test.dat中。

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
    FILE *fp;
    char ch;
    int daxie=0,xiaoxie=0,shuzi=0,qita=0;
    if((fp=fopen("src.dat","r"))==NULL)//这个src文件需要自己去建立,另一个同理 
    {
        printf("File open error!\n");
        exit(0);  //退出程序 
    }
    while(feof(fp)==0)  // feof (函数名)文件结束:返回非0值,文件未结束,返回0值
    {
        ch=fgetc(fp);
        if(ch>='A'&&ch<='Z')
            daxie++;
        else if(ch>='a'&&ch<='z')
            xiaoxie++;
        else if(ch>='0'&&ch<='9')
            shuzi++;
        else
            qita++;
    }
    if((fp=fopen("test.dat","w"))==NULL)
    {
        printf("File open error!\n");
        exit(0);
    }
    fprintf(fp,"大写=%d\n 小写=%d\n 数字=%d\n 其它=%d\n",daxie,xiaoxie,shuzi,qita);
    if(fclose(fp))
    {
        printf("Can not close the file!\n");
        exit(0);
    }
    return 0;
}

程序二

输出文本文件input.txt中的非空格字符。

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
    FILE *fp;
    char ch;
    if((fp=fopen("input.txt","r"))==NULL)
    {
        printf("File open error!\n");
        exit(0);
    }
    while(feof(fp)==0)
    {
        ch=fgetc(fp);
        if(ch!=' ')
        {
            putchar(ch);//输出字符 
        }
    }
    printf("\n");
    if(fclose(fp))
    {
        printf("Can not close the file!\n");
        exit(0);
    }
    return 0;
}

程序三

在6至10000内找出所有的合数,并顺序将每个合数用语句fprintf(p,”%6d”,n)写入到新建的文件design.dat,(要求文件名由命令行输入,如HeShu design.dat,其中HeShu为可执行文件名(这个要求可以不做))。(合数是指一个数等于除它本身外所有因数的和,如6=1+2+3,28=1+2+4+7+14)

#include <stdio.h>
#include <stdlib.h>
int sort(int n){
    int i,j,sum=0;
    for(i=1;i<=n-1;i++){
        if(n%i==0){
            sum=sum+i;
        }
    }
    if(sum==n){
        return 1;
    }
    else
        return 0;
}
int main()
{
    FILE *p;
    int n,i,j;
    if((p=fopen("design.dat","wb"))==NULL){
        printf("File open error!\n");
        exit(0);
    }
    for(i=6;i<=10000;i++){
        if(sort(i)){
            printf("%6d",i);
            fprintf(p,"%6d",i);
        }
    }
    if(fclose(p)){
        printf("File close error!\n");
        exit(0);
    }
    return 0;
}

 

程序四

有一个文件t.dat,请编写一程序,将t.dat中的所有小写英文字母转换成大写英文字母,其它字符不作转换,原样存储。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *p;
    char ch[1000];
    int i=0,n;
    if((p=fopen("t.dat","r"))==NULL)
    {
        printf("File open error!\n");
        exit(0);
    }
    while(feof(p)==0)
    {
        ch[i]=fgetc(p);
        i++;
    }
    n=i;
    for(i=0;i<=n;i++)
    {
        if(ch[i]>='a'&&ch[i]<='z')
        {
        ch[i]=ch[i]-32;
        }
    }
    if((p=fopen("t.dat","w"))==NULL)
    {
        printf("File open error!\n");
        exit(0);
    }
    for(i=0;i<=n;i++)
    {
        fprintf(p,"%c",ch[i]);
    }
    if(fclose(p))
    {
        printf("File close error!\n");
        exit(0);
    }
    return 0;
}

 

推荐阅读