UNIXシステムコール 位置決めをしてファイルに書く(ヌルバイトを作る)
ファイルに、3バイトの文字列を書き込んでファイルの書き込み位置を3バイト先へ進める、という処理を繰り返す。
プログラムを実行すると、いくつかの3バイトの文字列と3バイトのヌル文字列が書き込まれたファイルが作成される。
#include <sys/types.h> /* lseek, open, write */ #include <stdio.h> /* perror */ #include <stdlib.h> /* exit */ #include <sys/stat.h> /* open */ #include <fcntl.h> /* open */ #include <sys/uio.h> /* write */ #include <unistd.h> /* close, lseek, write */ int main(void) { int d, i; if ((d = open("hop.out", O_WRONLY|O_CREAT|O_TRUNC, 0666)) == -1) { perror("open"); exit(1); } for (i = 0; i < 8; i++) { if (write(d, "hop", 3) == -1) { perror("write"); exit(1); } if (lseek(d, 3, SEEK_CUR) == -1) { perror("lseek"); exit(1); } } close(d); return 0; }
$ cat hop.out hophophophophophophophop $ od -c -Ax hop.out 000000 h o p \0 \0 \0 h o p \0 \0 \0 h o p \0 000010 \0 \0 h o p \0 \0 \0 h o p \0 \0 \0 h o 000020 p \0 \0 \0 h o p \0 \0 \0 h o p 00002d