C語言作文件操常用代碼

fd5f 9年前發布 | 2K 次閱讀 C/C++

    ////////////////////////////////////////////////////////////////
打開文件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;  
}  </pre> 


附上讀寫方式:

 本文由用戶 fd5f 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!