マイtruncate続きです。
サイズの切り詰め処理は、truncateコマンドのソースを参考にしてみます。
「マイtruncateを作る(その3)」で知りましたが、truncateコマンドでは、ftruncate関数を使ってました。
static bool
do_ftruncate (int fd, char const *fname, off_t ssize, off_t
rel_mode_t rel_mode)
{
struct stat sb;
off_t nsize;
~省略~
if (ftruncate (fd, nsize) == -1) /* note updates mtim
{
error (0, errno,
_("failed to truncate %s at %" PRIdMAX " bytes"
(intmax_t) nsize);
return false;
}
return true;
}
使い方は、man 2 truncate。
TRUNCATE(2) Linux Programmer's Manual TRUNCATE(2)
名前
truncate, ftruncate - 指定した長さにファイルを切り詰める
書式
#include <unistd.h>
#include <sys/types.h>
int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);
マニュアルを見ると、truncate()と、ftruncate()があります。ftruncate()から使ってみます。
openしてftruncateしてcloseするだけです。
takk@deb9:~/tmp$ cat -n test.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 int fd;
9 fd = open("test.bin",O_RDWR);
10 ftruncate(fd,3);
11 close(fd);
12 return 0;
13 }
takk@deb9:~/tmp$
簡単に書けるんですね。
使ってみます。実験用データが本物のtruncateコマンドで生成します。
takk@deb9:~/tmp$ truncate -s10 test.bin takk@deb9:~/tmp$ wc -c test.bin 10 test.bin takk@deb9:~/tmp$ gcc test.c takk@deb9:~/tmp$ ./a.out takk@deb9:~/tmp$ wc -c test.bin 3 test.bin takk@deb9:~/tmp$
次は、truncate()を使ってプログラミングしてみます。
takk@deb9:~/tmp$ cat -n test.c
1 #include <unistd.h>
2 #include <sys/types.h>
3
4 int main()
5 {
6 truncate("test.bin",3);
7 return 0;
8 }
takk@deb9:~/tmp$
さらに簡単になりました。openもcloseもいらないのですね。
takk@deb9:~/tmp$ truncate -s10 test.bin takk@deb9:~/tmp$ wc -c test.bin 10 test.bin takk@deb9:~/tmp$ gcc test.c takk@deb9:~/tmp$ ./a.out test.bin takk@deb9:~/tmp$ ls -l test.bin -rw-r--r-- 1 takk takk 3 4月 19 19:46 test.bin takk@deb9:~/tmp$ wc -c test.bin 3 test.bin takk@deb9:~/tmp$
動きました。素晴らしい。



コメント