C語IO操作

6737 ワード

標準IO
demo
このプログラムでは、コードが存在するディレクトリの前のレベルのディレクトリのa.txtというファイルを開き、中のデータを読み出してコマンドラインに印刷し、a.txtと同じフォルダの下のb.txtファイルにデータを格納します.

#include 

int main()
{
    // fopen                。
    FILE *file = fopen("../a.txt", "r+");
    FILE *file_b = fopen("../b.txt", "a+");

    if (file == NULL || file_b == NULL)
    {
        //       
        fprintf(stderr, "     ");
        return -1;
    }
    int ch;
    //     EFO
    while ((ch = getc(file)) != EOF)
    {
        putchar(ch);
        putc(ch, file_b);
    }
    //            0,    EFO`
    int result = fclose(file);
    fclose(file_b);
    if (result != 0)
    {
       fprintf(stderr, "        ");
    }
    
    return 0;
}



共通API詳細
  • fopen("fileNmae", "mode")
    extern FILE *fopen (const char *__restrict __filename,
    		    const char *__restrict __modes) __wur;
    /* Open a file, replacing an existing stream with it.
    
       This function is a possible cancellation point and therefore not
       marked with __THROW.  */
    
    
    
  • 最初のパラメータは、ファイルを開くファイル名
  • です.
  • の2番目のパラメータは、ファイルを開くモード
  • である.
  • 戻り値:
  • ファイルを正常に開いてファイルポインタ
  • に戻りました.
  • 失敗オープン戻り空ポインタ

  • getc() & putc()
    extern int getc (FILE *__stream);
    
    /* Read a character from stdin.
    
       This function is a possible cancellation point and therefore not
       marked with __THROW.  */
    extern int putc (int __c, FILE *__stream);
    
    /* Write a character to stdout.
    
       This function is a possible cancellation point and therefore not
       marked with __THROW.  */
    
  • getc()関数がファイルの最後に読み込まれるとEOFに戻ります.これを判断の対象として、ファイルの読み取りが終了したかどうかを確認します.