-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.c
More file actions
31 lines (27 loc) · 829 Bytes
/
Copy pathfile.c
File metadata and controls
31 lines (27 loc) · 829 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "9cc.h"
// 指定されたファイルの内容を返す
char *read_file(char *path) {
// ファイルを開く
FILE *fp = fopen(path, "r");
if (!fp)
error("cannot open %s: %s", path, strerror(errno));
// ファイルの長さを調べる
if (fseek(fp, 0, SEEK_END) == -1)
error("%s: fseek: %s", path, strerror(errno));
size_t size = ftell(fp);
if (fseek(fp, 0, SEEK_SET) == -1)
error("%s: fseek: %s", path, strerror(errno));
// ファイル内容を読み込む
char *buf = calloc(1, size + 2);
fread(buf, size, 1, fp);
// ファイルが必ず"\n\0"で終わっているようにする
if (size == 0 || buf[size - 1] != '\n')
buf[size++] = '\n';
buf[size] = '\0';
fclose(fp);
return buf;
}