ヒントになればと思い自己流にて作成してみました。(一応メモリに読み込んでいる)
c
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4#include <fcntl.h>
5#include <sys/stat.h>
6
7//ファイルサイズと行数を取得する
8int GetFileSize(char *file, int *size, int *line)
9{
10 FILE *fp;
11 int c;
12 *line = *size = 0;
13
14 if ((fp = fopen(file, "r")) == NULL) return 1;
15 while ((c = fgetc(fp)) != EOF) {
16 if (c == '\n') (*line)++;
17 (*size)++;
18 }
19 fclose(fp);
20 return 0;
21}
22
23void main(int argc, char** argv)
24{
25 int size;
26 int line;
27 int i;
28
29 char* file = argv[1];
30 printf("debug0 %s \n", file);
31 if (GetFileSize(file, &size, &line)) exit(1);
32 printf ("size:%d line:%d \n",size, line);
33
34 char* buff = (char *)malloc(sizeof(char)*size+1); // ファイル全体メモリ確保
35 memset(buff, 0x00, sizeof(char)*size+1);
36
37 int fd = open(file, O_RDONLY); // ファイルを開く
38 if (fd == -1) exit(1);
39
40 int rc = read(fd, buff, sizeof(char)*size); // サイズ分確保
41 close(fd); // ファイルを閉じる
42
43 const char* kaigyo = "\n";
44 char** ptr = (char **)malloc(sizeof(char*)*line); // 行分のデータ確保
45 char** p = ptr;
46 *p = strtok(buff, kaigyo); // ファイルを改行で分割
47 while ((*p) != NULL) {
48 p++;
49 *p = strtok(NULL, kaigyo);
50 }
51
52 for(i=0; i<line; i++) printf("%s\n", ptr[i]); // データの利用
53
54 free(buff); // メモリ解放
55 free(ptr);
56}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。