分享

C语言作文件操常用代码

 心不留意外尘 2016-04-27
http://www./code/view/1419839606375
2014.12 
   //////////////////////////////////////////////// 
    打开文件fopen  
        函数原型: FILE *fopen(char  *name,char *mode)  
        功能:按指定方式打开文件  
        返值:正常打开,为指向文件结构体的指针;打开失败,为NULL  
    文件关闭fclose  
        函数原型:int fclose(FILE  *fp)  
        功能:关闭fp指向的文件  
        返值:正常关闭为0;出错时,非0  
    //  
        文件读取方式  
    //方法一  
       
     FILE *fp;          //定义一个文件类型指针  
          fp=fopen("aa.c","w");       //打开一个文件 打开方式为w(只写.文本文件)  aa.c为相对路径  
          if(fp==NULL)    //判断文件打开是否成功  
          {       
             printf("File open error!\n");       
             exit(0);        //终止程序 区别于return  
          }  
           
    //方法二  
      
    FILE  *fp;  
         fp= fopen ("c:\\fengyi\\bkc\\test.dat","r");     //绝对路径  打开方式为r(只读.文本文件)  
              
    //方法三  
      
     FILE  *fp;  
            char  *filename="c:\\fengyi\\bkc\\test.dat"  
            fp= fopen(filename,”r”);  
    //////////////////////////////////////////////// 
    fputc与fgetc  
        fputc:  
        函数原型:int fputc(int c, FILE *fp)  
        功能:把一字节代码c写入fp指向的文件中  
        返值:正常,返回c;出错,为EOF  
         fgetc  
        函数原型:int fgetc(FILE *fp)  
        功能:从fp指向的文件中读取一字节代码  
        返值:正常,返回读到的代码值;读到文件尾或出错,为EOF         
    //  
    从键盘输入字符,逐个存到磁盘文件中,直到输入“#”为止   
    #include <stdio.h>  
    int main()  
    {    
        FILE *fp;  
        char ch,*filename="out.txt";  
        if((fp=fopen(filename,"w"))==NULL)             //打开文件失败  
        {     
            printf("cannot open file\n");  
            exit(0);  
        }  
        printf("Please input string:");  
        ch=getchar();  
        while(ch!='#')  
        {       
              fputc(ch,fp);  
              putchar(ch);  
              ch=getchar();  
        }  
        fclose(fp);           //操作完后一定要关闭文件,一面数据丢失  
        return 0;  
    }  
    //  
    读文本文件内容,并显示  
    #include <stdio.h>  
    int main()  
    {    
        FILE *fp;  
        char ch,*filename="out.txt";  
        if((fp=fopen(filename,"r"))==NULL)  
        {     
            printf("cannot open file\n");  
            exit(0);  
        }  
        while((ch=fgetc(fp))!=EOF)  
            putchar(ch);  
        fclose(fp);  
        return 0;  
    }  
    //  
    文件拷贝  
    #include <stdio.h>  
    int main()  
    {     
       FILE *in, *out;  
       char ch,infile[10],outfile[10];  
       scanf("%s",infile);  
       scanf("%s",outfile);  
       if ((in = fopen(infile, "r"))== NULL)  
       {   
          printf("Cannot open infile.\n");  
          exit(0);  
       }  
       if ((out = fopen(outfile, "w"))== NULL)  
       {   
          printf("Cannot open outfile.\n");  
          exit(0);  
       }  
       while (!feof(in))  
            fputc(fgetc(in), out);     //fgetc(in)返回一个字符光标向下移动一位,fputc(ch,fp)将字符输入到fp指向文件中光标始终留在最后;  
       fclose(in);     
       fclose(out);  
       return 0;  
    }  
      
    //////////////////////////////////////////////// 
    数据块的输入输出:fread与fwrite  返值:成功,返回读/写的块数;出错或文件尾,返回0  
      
    //  
       float  f[2];  
          FILE  *fp;  
          fp=fopen("aa.dat","rb");  
          fread(f,4,2,fp);  
    //  
    for(i=0;i<2;i++)  
        fread(&f[i],4,1,fp);  
    //  
     struct student  
      {    int num;  
           char  name[20];  
           char sex;  
           int age;  
           float  score[3];  
      }stud[10];  
     for(i=0;i<10;i++)  
          fread(&stud[i],sizeof(struct  student),1,fp);  
    //  
    从键盘输入4个学生数据,把他们转存到磁盘文件中去  
    #include <stdio.h>  
    #define SIZE 4  
    struct student_type  
    {    char name[10];  
         int num;  
         int age;  
         char addr[15];  
    }stud[SIZE];  
    int main()  
    {  
         int i;  
         for(i=0;i<SIZE;i++)  
         scanf("%s%d%d%s",stud[i].name,&stud[i].num,  
                 &stud[i].age,stud[i].addr);  
         save();  
         display();  
         return 0;  
    }  
    void display()  
    {   FILE *fp;  
         int  i;  
         if((fp=fopen("d:\\fengyi\\exe\\stu_dat","rb"))==NULL)  
         {      
            printf("cannot open file\n");  
            return;  
         }  
         for(i=0;i<SIZE;i++)  
         {     
             fread(&stud[i],sizeof(struct student_type),1,fp);  
             printf("%-10s %4d %4d %-15s\n",stud[i].name,  
                     stud[i].num,stud[i].age,stud[i].addr);  
         }  
         fclose(fp);  
    }  
    void save()  
    {   FILE *fp;  
         int  i;  
         if((fp=fopen("d:\\fengyi\\exe\\stu_dat","wb"))==NULL)  
         {      
            printf("cannot open file\n");  
            return;  
         }  
         for(i=0;i<SIZE;i++)  
             if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)  
             printf("file write error\n");  
         fclose(fp);  
    }  
    ////////////////////////////////////////////// 
    格式化I/O:fprintf与fscanf    返值:成功,返回I/O的个数;出错或文件尾,返回EOF  
    //  
          fprintf(fp,"%d,%6.2f",i,t);     //将i和t按%d,%6.2f格式输出到fp文件  
          fscanf(fp,"%d,%f",&i,&t);    //若文件中有3,4.5  ,则将3送入i, 4.5送入t  
    //  
    从键盘按格式输入数据存到磁盘文件中去  
    #include <stdio.h>  
    int main()  
    {   
       char s[80],c[80];  
       int a,b;  
       FILE *fp;  
       if((fp=fopen("test","w"))==NULL)  
       {     
          puts("can't open file");    
          exit() ;   
       }  
       fscanf(stdin,"%s%d",s,&a);/*read from keaboard*/  
       fprintf(fp,"%s  %d",s,a);/*write to file*/  
       fclose(fp);  
       if((fp=fopen("test","r"))==NULL)  
       {     
          puts("can't open file");   
          exit();     
       }  
       fscanf(fp,"%s%d",c,&b);/*read from file*/  
       fprintf(stdout,"%s %d",c,b);/*print to screen*/  
       fclose(fp);  
       return 0;  
    }  
    ////////////////////////////////////////////// 
    字符串I/O: fgets与fputs    
    返值:  
        fgets正常时返回读取字符串的首地址;出错或文件尾,返回NULL  
        fputs正常时返回写入的最后一个字符;出错为EOF  
    //  
    从键盘读入字符串存入文件,再从文件读回显示  
    #include<stdio.h>  
    int main()  
    {     
        FILE  *fp;  
        char  string[81];  
        if((fp=fopen("file.txt","w"))==NULL)  
        {     
            printf("cann't open file");  
            exit(0);   
        }  
        while(strlen(gets(string))>0)  
        {   fputs(string,fp);  
            fputs("\n",fp);  
        }  
        fclose(fp);  
        if((fp=fopen("file.txt","r"))==NULL)  
        {     
            printf("cann't open file");  
            exit(0);   
        }  
        while(fgets(string,81,fp)!=NULL)  
           fputs(string,stdout);  
        fclose(fp);  
        return 0;  
    }  
    /////////////////////////////////////////////// 
    文件的定位  
        rewind函数  
            函数原型:  void  rewind(FILE  *fp)  
            功能:重置文件位置指针到文件开头  
            反值:无  
    //  
    对一个磁盘文件进行显示和复制两次操作  
    #include <stdio.h>  
    int main()  
    {     
        FILE *fp1,*fp2;  
        fp1=fopen("d:\\fengyi\\bkc\\ch12_4.c","r");  
        fp2=fopen("d:\\fengyi\\bkc\\ch12_41.c","w");  
        while(!feof(fp1))    
        putchar(getc(fp1));  
        rewind(fp1);  
        while(!feof(fp1))    
        putc(getc(fp1),fp2);  
        fclose(fp1);  
        fclose(fp2);  
        return 0;  
    }  
    //  
    fseek函数  
        函数原型:  int  fseek(FILE  *fp,long  offset,int whence)  
        功能:改变文件位置指针的位置  
        返值:成功,返回0;失败,返回非0值  
        offset:  
        位移量(以起始点为基点,移动的字节数)  
        >0    向后移动  
        <0    向前移动  
        whence:  
        起始点  
        文件开始              SEEK_SET    0  
        文件当前位置            SEEK_CUR    1  
        文件末尾              SEEK_END    2  
    ftell函数  
        函数原型:  long  ftell(FILE  *fp)  
        功能:返回位置指针当前位置(用相对文件开头的位移量表示)  
        返值:成功,返回当前位置指针位置;失败,返回-1L,  
    //  
    磁盘文件上有3个学生数据,要求读入第1,3学生数据并显示  
    #include <stdio.h>  
    struct student_type  
    {    int num;  
         char name[10];  
         int age;  
         char addr[15];  
    }stud[3];  
    int main()  
    {     
        int i;  
        FILE *fp;  
        if((fp=fopen("studat","rb"))==NULL)  
        {     
            printf("can't open file\n");  
            exit(0);     
        }  
        for(i=0;i<3;i+=2)  
        {     
             fseek(fp,i*sizeof(struct student_type),0);  
             fread(&stud[i],sizeof(struct student_type),1,fp);  
             printf("%s  %d  %d  %s\n",  
               stud[i].name,stud[i].num,stud[i].age,stud[i].addr);  
        }  
        fclose(fp);  
        return 0;  
    }  
    //  
    求文件长度(ch12_101.c)  
    #include"stdio.h"  
    int main()  
      {   
        FILE *fp;  
        char filename[80];  
        long length;  
        gets(filename);  
        fp=fopen(filename,"rb");  
        if(fp==NULL)  
           printf("file not found!\n");  
        else  
        {   
          fseek(fp,0L,SEEK_END);  
          length=ftell(fp);  
          printf("Length of File is %1d bytes\n",length);  
          fclose(fp);  
        }  
        return 0;  
      }  
    //////////////////////////////////////////////// 
    出错的检测  
    ferror函数  
        函数原型:   int  ferror(FILE  *fp)  
        功能:测试文件是否出现错误  
        返值:未出错,0;出错,非0  
        说明  
            每次调用文件输入输出函数,均产生一个新的ferror函数值,所以应及时测试  
            fopen打开文件时,ferror函数初值自动置为0  
    clearerr函数  
        函数原型:   void  clearerr(FILE  *fp)  
        功能:使文件错误标志置为0  
        返值:无  
        说明:出错后,错误标志一直保留,直到对同一文件调clearerr(fp)或rewind或任何其它一个输入输出函数  
    //  
    ferror()与clearerr()举例  
    #include <stdio.h>  
    int  main(void)  
    {    
       FILE *stream;  
       stream = fopen("DUMMY.FIL", "w");  
       getc(stream);  
       if (ferror(stream))  
       {    
          printf("Error reading from DUMMY.FIL\n");  
          clearerr(stream);  
       }  
       if(!ferror(stream))  
           printf("Error indicator cleared!");  
       fclose(stream);  
       return 0;  
    }  

附上读写方式:

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多