2009-04-24 19:10

[C語言] 檔案讀寫

fclose , feof , fopen , fprintf , fscanf , printf , remove , rename , rewind , scanf , ftell , fseek
  1. #include <stdio.h> 
  2.  
  3. int main(){ 
  4.    FILE *fileIn; 
  5.    FILE *fileOut; 
  6.  
  7.    fileIn = fopen("input.txt", "r"); 
  8.    if(fileIn == NULL){printf("檔案不存在\n"); return 0;} 
  9.  
  10.    fileOut = fopen("output.txt", "w"); 
  11.    /* Mod: 
  12.    * "r" : 開啟檔案,以純文字方式[讀取]。 
  13.    * "w" : 開啟或建立檔案,以純文字方式[寫入],會複寫原先的資料。 
  14.    * "a" : 開啟或建立檔案,以純文字方式[寫入],並將檔案指標移到最後。 
  15.    * "rb" : 同 "r" 但以二進位(binary)方式[讀取]。 
  16.    * "wb" : 同 "w" 但以二進位(binary)方式[寫入]。 
  17.    * "ab" : 同 "a" 但以二進位(binary)方式[寫入]。 
  18.    * "r+" : 同 "r" 但同時具有[讀取/寫入]的權力 
  19.    * "w+" : 同 "w" 但同時具有[讀取/寫入]的權力 
  20.    * "a+" : 同 "a" 但同時具有[讀取/寫入]的權力 
  21.    * "rb+" : 同 "rb" 但同時具有[讀取/寫入]的權力 
  22.    * "wb+" : 同 "wb" 但同時具有[讀取/寫入]的權力 
  23.    * "ab+" : 同 "ab" 但同時具有[讀取/寫入]的權力。 
  24.    */ 
  25.  
  26.  
  27.    int    a1; 
  28.    float  a2; 
  29.    char   a3; 
  30.    char   a4[100]; 
  31.  
  32.    while(!feof(fileIn)){// 當讀取結束時會回傳 true 
  33.        // 依格式讀取一列文字,所有的變數都要取址,除了字元陣列 
  34.        fscanf(fileIn,"%d %f %c %s",&a1,&a2,&a3,a4); 
  35.  
  36.        // 依格式將資料輸出至螢幕上 
  37.        printf("%d %f %c %s\n",a1,a2,a3,a4); 
  38.  
  39.        // 依格式寫入一列文字 
  40.        fprintf(fileOut,"%d %f %c %s\n",a1,a2,a3,a4); 
  41.  
  42.        /* %c : 一個字元(char)格式 
  43.        * %s : 一個字串格式 
  44.        * 
  45.        * %i : 一個整數(int)格式 
  46.        * %d : 一個十進位整數(int)格式 
  47.        * %u : 一個十進位無符號整數(unsigned)格式 
  48.        * 
  49.        * %e, %f, %g : 一個浮點數(float)格式 
  50.        * %lf: 一個浮點數(double)格式 
  51.        * 
  52.        * %o : 八進位(02732)格式 
  53.        * %x : 十六進位(0x27fa)格式 
  54.        * %% : 跳脫成 % 
  55.        * */ 
  56.  
  57.    } 
  58.  
  59.    // 輸出當前的檔案指標位址 
  60.    printf("offset = %ld\n", ftell(fileIn) ); 
  61.  
  62.    // 將檔案指標返回至最上面,失敗則回傳 0 
  63.    // 會清除錯誤並將 EOF 標示清除 
  64.    // 當需要重新讀取時可利用此函數 
  65.    rewind(fileIn); 
  66.  
  67.    // 將移動檔案指標從開始處偏移 5 個字元,成功則回傳 0 
  68.    // 會將 EOF 標示清除 
  69.    fseek(fileIn,5,SEEK_SET); 
  70.    /* int fseek( FILE *stream, long offset, int origin ); 
  71.    * stream : 檔案指標 
  72.    * offset : 偏移量,可為正負數 
  73.    * origin : 偏移的依據位址 
  74.    *   SEEK_SET 0  檔案起始位址 
  75.    *   SEEK_CUR  1  當前位址 
  76.    *   SEEK_END  2  檔案結束位址 
  77.    * */ 
  78.  
  79.  
  80.    // 關閉檔案指標 
  81.    fclose(fileIn); 
  82.    fclose(fileOut); 
  83.  
  84.    // 將檔案 "input.txt" 移除 
  85.    remove("input.txt"); 
  86.  
  87.    // 將 "output.txt" 的檔案名稱變更為 "input.txt" 
  88.    rename("output.txt","input.txt"); 
  89.  
  90.  
  91.    // 按任意鍵結束 
  92.    _getch(); 
  93.    return 0; 
  94. } 


參考來源:
Standard C I/O [C++ Reference]
printf() 與 scanf()

0 回應: