このエントリーをはてなブックマークに追加


テキストファイルを行単位で読み込む・fgets

テキストファイルを行単位読み込むCサンプルコードを以下に記します。
行単位の読み込みで使用する関数はfgetsになります。


スポンサーリンク

関連記事

fgetsの書式等

  • 必要なインクルードファイル
    #include <stdio.h>
  • fgetsの書式
    char *fgets(char *s, int size, FILE *stream);
  • 戻り値
    読み込んだ行のあとのポインタ(アドレス)を返却する。
  • 引数
    1つ目: ファイルから読み込んだ1行を格納するバッファのポインタ
    2つ目: 1つ目の引数で渡したバッファのサイズ
    3つ目: ファイルハンドル(ファイルポインタ)

fgetsを使用したC言語サンプルコード

filefgets.c (改行コードLF)

#include <stdio.h>

#define BUF4K 4096

void usage(char *cmd)
{
    fprintf(stderr, "Usage: %s <text file>\n", cmd);
}


int main(int argc, char *argv[])
{
    FILE *fh = NULL;
    char buf[BUF4K];

    if (argc != 2) {
        usage(argv[0]);
        return 1;
    }
    
    fh = fopen(argv[1], "r");
    if (fh == NULL) {
        fprintf(stderr, "%s is not found.\n", argv[1]);
        return 1;
    }

    /* fgets sample code body */
    while (fgets( buf, BUF4K, fh) != NULL) {
        printf("%s", buf);
    }

    if (fh != NULL) {
        fclose(fh);
    }
}

コンパイルおよび実行した結果は以下の通りです。
尚、本C言語サンプルコードは引数にテキストファイル名を指定します。
以下の例では/etc/hostsを指定しています。

$ gcc fgets.c -o fgets
sakura@mini:~/c$ ./fgets /etc/hosts
127.0.0.1	localhost mini
#127.0.1.1	mini

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

以上、ファイルを1行単位で読み込むfgets関数でした。


スポンサーリンク

添付ファイル: filefgets.c 517件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2015-03-20 (金) 21:01:00