2009-04-24 19:10

[C語言] 檔案讀寫

fclose , feof , fopen , fprintf , fscanf , printf , remove , rename , rewind , scanf , ftell , fseek
#include <stdio.h>

int main(){
    FILE *fileIn;
    FILE *fileOut;

    fileIn = fopen("input.txt", "r");
    if(fileIn == NULL){printf("檔案不存在\n"); return 0;}

    fileOut = fopen("output.txt", "w");
    /* Mod:
    * "r" : 開啟檔案,以純文字方式[讀取]。
    * "w" : 開啟或建立檔案,以純文字方式[寫入],會複寫原先的資料。
    * "a" : 開啟或建立檔案,以純文字方式[寫入],並將檔案指標移到最後。
    * "rb" : 同 "r" 但以二進位(binary)方式[讀取]。
    * "wb" : 同 "w" 但以二進位(binary)方式[寫入]。
    * "ab" : 同 "a" 但以二進位(binary)方式[寫入]。
    * "r+" : 同 "r" 但同時具有[讀取/寫入]的權力
    * "w+" : 同 "w" 但同時具有[讀取/寫入]的權力
    * "a+" : 同 "a" 但同時具有[讀取/寫入]的權力
    * "rb+" : 同 "rb" 但同時具有[讀取/寫入]的權力
    * "wb+" : 同 "wb" 但同時具有[讀取/寫入]的權力
    * "ab+" : 同 "ab" 但同時具有[讀取/寫入]的權力。
    */


    int    a1;
    float  a2;
    char   a3;
    char   a4[100];

    while(!feof(fileIn)){// 當讀取結束時會回傳 true
        // 依格式讀取一列文字,所有的變數都要取址,除了字元陣列
        fscanf(fileIn,"%d %f %c %s",&a1,&a2,&a3,a4);

        // 依格式將資料輸出至螢幕上
        printf("%d %f %c %s\n",a1,a2,a3,a4);

        // 依格式寫入一列文字
        fprintf(fileOut,"%d %f %c %s\n",a1,a2,a3,a4);

        /* %c : 一個字元(char)格式
        * %s : 一個字串格式
        *
        * %i : 一個整數(int)格式
        * %d : 一個十進位整數(int)格式
        * %u : 一個十進位無符號整數(unsigned)格式
        *
        * %e, %f, %g : 一個浮點數(float)格式
        * %lf: 一個浮點數(double)格式
        *
        * %o : 八進位(02732)格式
        * %x : 十六進位(0x27fa)格式
        * %% : 跳脫成 %
        * */

    }

    // 輸出當前的檔案指標位址
    printf("offset = %ld\n", ftell(fileIn) );

    // 將檔案指標返回至最上面,失敗則回傳 0
    // 會清除錯誤並將 EOF 標示清除
    // 當需要重新讀取時可利用此函數
    rewind(fileIn);

    // 將移動檔案指標從開始處偏移 5 個字元,成功則回傳 0
    // 會將 EOF 標示清除
    fseek(fileIn,5,SEEK_SET);
    /* int fseek( FILE *stream, long offset, int origin );
    * stream : 檔案指標
    * offset : 偏移量,可為正負數
    * origin : 偏移的依據位址
    *   SEEK_SET 0  檔案起始位址
    *   SEEK_CUR  1  當前位址
    *   SEEK_END  2  檔案結束位址
    * */


    // 關閉檔案指標
    fclose(fileIn);
    fclose(fileOut);

    // 將檔案 "input.txt" 移除
    remove("input.txt");

    // 將 "output.txt" 的檔案名稱變更為 "input.txt"
    rename("output.txt","input.txt");


    // 按任意鍵結束
    _getch();
    return 0;
}



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

0 回應: