テキストファイルを行単位読み込むCサンプルコードを以下に記します。
行単位の読み込みで使用する関数はfgetsになります。
#include <stdio.h>
char *fgets(char *s, int size, FILE *stream);
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関数でした。