c语言----文件的操作及应用(2)

来源:互联网 发布:刘清华踮脚看航母 知乎 编辑:程序博客网 时间:2024/06/05 15:35

 

            先打开fp=fopen(“”,“”);

           再操作,写入fputc(ch,fp),读出ch=fgetc(fp);

          从键盘读取字符是ch=getchar();将字符显示在屏幕上是putchar(ch);

 

1、从键盘中输入一个字符串,并逐个将字符串的每个字符传送到磁盘文件11.txt中,字符串的结束标记为“#”;

       #include <stdio.h>
#include <stdlib.h>
void main()
{   char ch;
    if((fp=fopen("d:\\11.txt","w"))==NULL)
    {
        printf("can't open\n");
        exit(0);
    }
     printf("enter the data:\n");
    while((ch=getchar())!='#')
      fputc(ch,fp);
      fclose(fp);
    }

2、有一个文本文件11.txt,请编写一个程序将文件中的英文字母及数字字符显示在屏幕上;


#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;
    char ch;
    if((fp=fopen("d:\\11.txt","r"))==NULL)
    {
        printf("can't open\n");
        exit(0);
    }
    while(!feof(fp)){
        ch = fgetc(fp);
        if(ch>='A'&&ch<='Z'||ch>='a'&&ch<='z'||ch>='0'&&ch<='9')
            putchar(ch);
    }
    fclose(fp);
    return 0;
    }

ps:补充知识:

                feof()函数是我们在C语言中操作文件经常用到的一个函数。这个函数用来表示我们是否已经到了文件的末尾的下一个位置。不管是二进制文件,还是文本文件它都管用。对比EOF(一般宏定义为-1),EOF只能用来判断文本文件是否到达末尾,因为文本文件中的数字是用ASCII表示的,ASCII字符的取值范围是0~255。而二进制文件中可能存在-1,所以不能用EOF来判断结束。

我们使用feof经常遇到的一个问题是,用fgets读文件,然后用fputs打印。最后一行会打印两遍。

这是为什么了?

先说一下feof()函数

在stdio.h里有feof的定义:
#define _IOEOF 0x0010
#define feof(_stream) ((_stream)->_flag _IOEOF)

由此可知只有当_flag=_IOEOF时,feof()才会返回1。在VC里,只有当 file position indicator(在Windows上是fp->_ptr)到了文件末尾,然后再发生读/写操作时,fp-> _flag才会被置为含有_IOEOF,然后再调用feof(),才会得到文件结束的信息。并不是file position indicator一指到文件尾,feof()就认为文件结束。也就是说只有文件指针到了文件末尾的下一个位置,feof()才会返回1。

 

3、把文本文件11.txt中的数字字符复制到文本文件12.txt中;

#include <stdio.h>
#include <stdlib.h>
void main()
{
    FILE *fp1;
    FILE *fp2;
    char ch;
    if((fp1=fopen("d:\\11.txt","r"))==NULL||(fp2=fopen("d:\\12.txt","w"))==NULL)
    {
        printf("can't open \n");
        exit(0);
    }
    while((ch =fgetc(fp1))!=EOF){
       if (ch>='0'&&ch<='9')
        fputc(ch,fp2);
      }
      fclose(fp1);
      fclose(fp2);
    }
notice判断语句 比较关键

4、将x从0到360度的sin(x)值写入到文件16.txt中,并将大于0的值显示在屏幕上;

#include <stdio.h>
#include <stdlib.h>
#include<math.h>
int main()
{
    FILE *fp;
    int i;
    double y;
    if((fp=fopen("d:\\11.txt","w+"))==NULL){
        printf("can't open \n");
        exit(0);
    }
    for(i=0;i<360;i++){
        y=sin(3.14159*i/180);
        fprintf(fp,"%lf",y);
            if (y>0)
            printf("%lf\n",y);
    }
    fclose(fp);
    return 0;
    }

w+:w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。

fprintf:

5、编写程序:把20个字符输出到文本文件11.txt中,然后把文本11.txt中的字符写入一个字符数组中;

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;
    int i=20,j;
    int k=0;
    char ch,str[20];
    if((fp=fopen("d:\\11.txt","w"))==NULL)
    {
        printf("can't open\n");
        exit(0);
    }
    while(i--)
    {
        ch=getchar();
        fputc(ch,fp);
    }
    fclose(fp);
      if((fp=fopen("d:\\11.txt","r"))==NULL)
    {
        printf("can't open\n");
        exit(0);
    }
    while(!feof(fp)){
        ch=fgetc(fp);
        str[k++]=ch;
    }
    for(j=0;j<k;j++)
        printf("%c",str[j]);
    fclose(fp);
    return 0;
        }

 

6、编写程序:从键盘输入10个浮点数,以二进制形式存入文件13.txt中,并修改文件中序数为偶数的数据,所修改的数据从键盘输入;

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;
    int SIZE=10;
    float f=0.0,y[10];
    int i,j=0;
    for(i=0;i<SIZE;i++)         //y[i]初始化
        y[i]=0.000000;

    if((fp=fopen("d:\\13.txt","rb+"))==NULL)                             //“rb+”  读写打开一个二进制文件,允许读和写
    {
        printf("can't open\n");
        exit(0);
    }
    for(i=0;i<SIZE;i++)
    {
           scanf("%f",&f);
           y[i]=f;
           fprintf(fp,"%f",f);
       }
    for(i=0;i<SIZE;i=i+2)
    {
        printf("输入第%d需要修改的浮点数为: \n",i);
        y[i]=0.000000;
        scanf("%f",&f);
        y[i]=f;
       }
    for(i=0;i<SIZE;i++)
    {
        printf("%f ",y[i]);
       }
       rewind(fp);                       //rewind()函数  原型:void rewind(FILE *fp)        作用:使文件fp的位置指针指向文件开始。
    for(i=0;i<SIZE;i++)
    {
        fprintf(fp,"%f",f);
       }
       fclose(fp);
       return 0;
        }

 

7、在文本文件tx.txt中存放着一批自然数(总数不超过100),编写程序将文件中的数据读入数组,计算出所有偶数的平均值,并同时打印各位数之和大于10的数据。例如,tx。txt中有数据 123、234、345、456、567、678、789、890、901、012,得结果为:345、456、567、678、789、890、901、012

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;
    int ch,str[20];
    int i=0,j;
    int s=0;
    int count=0;
    int a,b,c,x;
    if((fp=fopen("d:\\tx.txt","r"))==NULL)
    {
        printf("can't open\n");
        exit(0);
    }
    while(!feof(fp))
    {
        fscanf(fp,"%d ",&ch);
        str[i++]=ch;
       // printf("%d\n",ch);
    }
    str[i]='\0';
    for(j=0;j<i;j++)
        printf("%d ",str[j]);
    for(j=0;j<i;j++)
        if(str[j]%2==0)
  {
             count=count+1;
            s=s+str[j];
    }
    printf("\n");
    printf("%d\n",(s/count));
   for(j=0;j<i;j++){
        a=str[j]%10;
        b=(str[j]/10)%10;
        c=str[j]/10/10;
        x=a+b+c;
        if(x>10)
            printf("%d\n",str[j]);
            }
    fclose(fp);
   return 0;
        }

 

、fscanf的用法 

  功 能: 从一个流中执行格式化输入

  用 法: int fscanf(FILE *stream, char *format,[argument...]);

  int fscanf(文件指针,格式字符串,输入列表);

  返回值:整型,数值等于[argument...]的个数

8、从文件file.dat中读入若干英文单词,按字母排序,输出到屏幕上。要求:可选择排序的单词,能对文件进行操作,采用函数和指针方式实现。(待定)

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define COUNT 40
#define LEN 40
#define MAZLEN (LEN+1)

int compar(const void *a,const void *b)
{
    char *aa=(char*) a,*bb=(char*)b;
    if(*aa>*bb)
        return 1;
    if(*aa=*bb)
        return 0;
    if(*aa<*bb)
        return -1;
              return 0;
}
int main()
{
  FILE *fp1;
  int cnt,i,len;
  char sel,buf[LEN],over;
  char b[COUNT][MAZLEN];
    if((fp=fopen("d:\\file.dat","r"))==NULL){

    printf("打开文件出错\n");
    exit(0);
  }
  cnt = 0;
  while(!feof(fp1)){
    fscanf(fp1,"%s",buf);
    printf("是否选择单词进行排序:%s?(y or n  )\n",buf);
    scanf("%c",&sel);
    scanf("%c",&over);
    if(sel=='y')
        len = strlen(buf);
        buf[len]='\0';
        qsort(buf,len,sizeof(char),compar);
        strcpy(b[cnt],buf);
        cnt ++;
  }
  for(i=0;i<cnt;i++)
  {
      printf("%s\n",b[i]);
  }
     }

补充:

 qsort 功 能: 使用快速排序例程进行排序

  用 法: void qsort(void *base, int nelem, int width, int (*fcmp)(const void *,const void *));

  参数:1 待排序数组首地址 2 数组中待排序元素数量 3 各元素的占用空间大小 4 指向函数的指针,用于确定排序的顺序

比如:对一个长为1000的数组进行排序时,int a[1000]; 那么base应为a,num应为 1000,width应为 sizeof(int),comp函数随自己的命名。

其中comp函数应写为:

  int comp(const void *a,const void *b)

  {

  return *(int *)a-*(int *)b;

  }

  上面是由小到大排序,return *(int *)b-*(int *)a; 为由大到小排序。

===============================================================================================================

一个典型的qsort的写法如下qsort(s,n,sizeof(s[0]),cmp);

  其中第一个参数是参与排序的数组名(或者也可以理解成开始排序的地址,因为可以写&s[i]这样的表达式);

  第二个参数是参与排序的元素个数;

  第三个参数是单个元素的大小,推荐使用sizeof(s[0])这样的表达式;

  第四个参数就是让很多人觉得非常困惑的比较函数啦,关于这个函数,还要说的比较麻烦...

  我们来讨论cmp这个比较函数(写成cmp是我的个人喜好,你可以随便写成什么,比如qcmp什么的).典型的cmp的定义是int cmp(const void *a,const void *b);

  返回值必须是int,两个参数的类型必须都是const void *,那个a,b是我随便写的,个人喜好.

  假设是对int排序的话,如果是升序,那么就是如果a比b大返回一个正值,小则负值,相等返回0,其他的依次类推,后面有例子来说明对不同的类型如何进行排序.

  下面举例:

  No.2.最常见的,对int数组排序

  #include <stdio.h>

  #include <string.h>

  #include <stdlib.h>

  int s[10000],n,i;

  int cmp(const void *a, const void *b)

  {

  return(*(int *)a-*(int *)b);

  }

  int main()

  {

  scanf("%d",&n);

  for(i=0;i<n;i++)

  scanf("%d",&s[i]);

  qsort(s,n,sizeof(s[0]),cmp);

  for(i=0;i<n;i++)

  printf("%d ",s[i]);

  return(0);

  }

strcpy原型声明:extern char *strcpy(char *dest,const char *src);

  头文件:string.h

  功能:把从src地址开始且含有NULL结束符的字符串赋值到以dest开始的地址空间

  说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。

  返回指向dest的指针。

9、对一个文件的内容进行加密操作(或解密操作),程序输入一串字符作为密钥,将文件内容与该字符串逐个字符对应相加(或相减),该密钥字符串循环使用,到串味再回到串首,而实现加密(或解密)。加密(解密)的结果存于另一文件并同时再屏幕上显示。(待定)

#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
    FILE *fp1;
    FILE *fp2;
    char s[100],ch,b[100];
    int i=0,j=0,k;
    if((fp1=fopen("d:\\11.txt","r+") )==NULL){                                 //r+ 以可读写方式打开文件,该文件必须存在。
        printf("打开文件出错11\n");
        exit(0);
    }
    if((fp2=fopen("d:\\12.txt","w+"))==NULL){                             // w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
        printf("打开文件出错12\n");
        exit(0);
    }
    printf("输入需要加密的密码:\n");
    scanf("%s",s);
    while(!feof(fp1)){
        ch=fgetc(fp1);
        if(j<strlen(s))
            b[i++]=ch+s[j++];
        else{
            j=0;
            b[i++]=ch+s[j++];
        }
    }
    b[--i]='\0';
    printf("加密后的文件为:%s\n",b);
    for(k=0;k<=i;k++)
        fputc(b[k],fp2);
    fclose(fp1);
    fclose(fp2);
    return 0;
     }

 

10、有两个磁盘文件a1和a2,各自存放一个已按字母顺序排号的字符串(如a1中存放“accel”,a2中存放“ilrz”),要求编写一个程序,实现两个文件的合并,合并后仍保持字母顺序(如“acceillrz”),并存放到a3文件中。

#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
    FILE *fp1;
    FILE *fp2;
    FILE *fp3;
    char ch,sum[100];
    int i=0,j=0,k;
    if((fp1=fopen("d:\\11.txt","r+"))==NULL){
        printf("打开文件出错11\n");
        exit(0);
    }
    if((fp2=fopen("d:\\12.txt","r+"))==NULL){
        printf("打开文件出错12\n");
        exit(0);
    }
    if((fp3=fopen("d:\\13.txt","w+"))==NULL){
        printf("打开文件出错12\n");
        exit(0);
    }
    while(!feof(fp1)){
        ch=fgetc(fp1);
        sum[i++]=ch;
    }
    i=i-2;
    while(!feof(fp2)){
        ch=fgetc(fp2);
        sum[i++]=ch;
    }
    sum[--i]='\0';
    printf("hebinghou :%s\n",sum);
    for(k=0;k<=i;k++)
    fputc(sum[k],fp3);
    fclose(fp1);
    fclose(fp2);
    fclose(fp3);
    return 0;
     }

 

原创粉丝点击