next up previous contents
Next: C 預處理器 Up: 輸入與輸出 Previous: 檔案開關   Contents

檔案讀寫

  1. 寫一個字元至檔案語法
    int fputc( int c, FILE *fp );
    
  2. 寫一個字串至檔案語法
    int fputs( const char *s, FILE *fp );
    
  3. 寫入檔案範例
    #include <stdio.h>
    
    main()
    {
       FILE *fp;
    
       fp = fopen("/tmp/test.txt", "w+");
       fprintf(fp, "This is testing for fprintf...\n");
       fputs("This is testing for fputs...\n", fp);
       fclose(fp);
    }
    

  4. 從檔案讀一個字元語法
    int fgetc( FILE * fp );
    
  5. 從檔案讀一個字串語法
    char *fgets( char *buf, int n, FILE *fp );
    
  6. 讀取檔案範例
    #include <stdio.h>
    
    main()
    {
       FILE *fp;
       char buff[255];
    
       fp = fopen("/tmp/test.txt", "r");
       fscanf(fp, "%s", buff);
       printf("1 : %s\n", buff );
    
       fgets(buff, 255, (FILE*)fp);
       printf("2: %s\n", buff );
       
       fgets(buff, 255, (FILE*)fp);
       printf("3: %s\n", buff );
       fclose(fp);
    
    }
    
  7. 二進位檔案讀取與寫入函式。
    size_t fread(void *ptr, size_t size_of_elements, 
                 size_t number_of_elements, FILE *a_file);
                  
    size_t fwrite(const void *ptr, size_t size_of_elements, 
                 size_t number_of_elements, FILE *a_file);
    switch(expression){
        case constant-expression  :
           statement(s);
           break; /* optional */
        case constant-expression  :
           statement(s);
           break; /* optional */
      
        /* you can have any number of case statements */
        default : /* Optional */
           statement(s);
    }
    
  8. 讀到檔案結束
    #include <stdio.h>
    #include <stdlib.h>
    
    int main( int argc, char *argv[] )
    {
        FILE *fp;
        int r1;
    
        fp = fopen(argv[1], "r");
        while (!feof(fp)){
            fscanf(fp, "%d ", &r1);
            printf("%d\n",r1);
        }
    }
    
  9. 執行結果
    [dywang@dyH gcctest]$ cat a.txt
    3 12 34 6 7
    [dywang@dyH gcctest]$ gcc argcsum.c && ./a.out a.txt 
    3
    12
    34
    6
    7
    
  10. 練習題:請寫一 C 語言程式,從命令列第一個參數指定的檔案讀取一串數字,印出共幾個數字及總和。
    例如:檔案中的數字為 3 12 34 6 7 輸出為:
    Ans=5,62


2015-01-16