前回確認したtruncateソースではopen、closeを直接使ってました。今回はopen、read、write、closeを使ってファイル読み込みをしたいと思います。
各関数の使い方はman 2 ~で確認しておきます。
OPEN(2) Linux Programmer's Manual OPEN(2)
名前
open, openat, creat - ファイルのオープン、作成を行う
書式
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);
int openat(int dirfd, const char *pathname, int flags);
int openat(int dirfd, const char *pathname, int flags, mode_t mode);
CLOSE(2) Linux Programmer's Manual CLOSE(2)
名前
close - ファイルディスクリプターをクローズする
書式
#include <unistd.h>
int close(int fd);
READ(2) Linux Programmer's Manual READ(2)
名前
read - ファイルディスクリプターから読み込む
書式
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
WRITE(2) Linux Programmer's Manual WRITE(2)
名前
write - ファイルディスクリプター (file descriptor)に書き込む
書式
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
manを参考にして組みます。全ソースです。
takk@deb9:~/tmp$ cat -n readwrite.c
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <fcntl.h>
4 #include <unistd.h>
5
6 int main()
7 {
8 char buf[100];
9 int fd;
10 int size;
11 fd = open ("test.dat", O_RDONLY);
12 while(1){
13 size = read(fd, buf, sizeof(buf));
14 if(size == 0)break;
15 write(1,buf,size);
16 }
17 close(fd);
18 return 0;
19 }
takk@deb9:~/tmp$
writeの第1引数は、ファイルディスクリプタですが、標準出力を指定したいので、1を渡しています。
読み込みファイルの作成。
takk@deb9:~/tmp$ seq 100 | pr -t5Jl1 > test.dat takk@deb9:~/tmp$
動かしてみます。ビルドして実行。
takk@deb9:~/tmp$ gcc readwrite.c takk@deb9:~/tmp$ ./a.out 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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 takk@deb9:~/tmp$
できました。


コメント