#navi(../)
* テキストファイルを行単位で読み込む・fgets [#v09b750b]
テキストファイルを行単位読み込むCサンプルコードを以下に記します。~
行単位の読み込みで使用する関数はfgetsになります。

#contents
#htmlinsertpcsp(c-top.html,c-sp.html)

* 関連記事 [#sf61ea8c]
-[[テキストファイルを行単位で読み込む・fgets>ファイル/テキストファイルを行単位で読み込む・fgets]]
-[[ディレクトリかどうか判別する・stat>ファイル/ディレクトリかどうか判別する・stat]]
-[[指定したディレクトリのファイル一覧を取得する・opendir,readdir>ファイル/指定したディレクトリのファイル一覧を取得する・opendir,readdir]]
-[[ファイルのサイズを取得する>ファイル/ファイルのサイズを取得する・stat]]
-[[ファイルのユーザIDとグループIDを取得する>ファイル/ファイルのUIDとGIDを取得する・stat]]
-[[fopenのファイルモード一覧表>ファイル/fopenのファイルモード一覧表]]
-[[バイナリファイルの書き込みと読み込み・fopen,fwrite,fread>ファイル/バイナリファイルの書き込みと読み込み・fopen,fwrite,fread]]

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

* fgetsを使用したC言語サンプルコード [#r84f56eb]
&ref(fgets.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関数でした。

#htmlinsertpcsp(c-btm.html,c-sp.html)

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS