UNIXシステムコール ファイルから読んで画面に表示する
#include <sys/types.h> /* open, read */ #include <stdio.h> /* perror, printf */ #include <stdlib.h> /* exit */ #include <sys/stat.h> /* open */ #include <fcntl.h> /* open */ #include <sys/uio.h> /* read */ #include <unistd.h> /* close, read */ int main(void) { int fd; char buf[6]; /* 5バイトの文字+ヌル文字*/ if ((fd = open("abc.txt", O_RDONLY)) == -1) { perror("open"); exit(1); } if (read(fd, buf, 5) != 5) { perror("read"); exit(1); } buf[5] = '\0'; printf("%s\n", buf); if (close(fd) == -1) { perror("close"); exit(1); } return 0; }
$ cat abc.txt abcdef
(gdb) b main Breakpoint 1 at 0x118d: file printfive.c, line 13. (gdb) r Breakpoint 1, main () at printfive.c:13 13 if ((fd = open("abc.txt", O_RDONLY)) == -1) { (gdb) n 18 if (read(fd, buf, 5) != 5) { (gdb) n 22 buf[5] = '\0'; (gdb) p buf $1 = "abcde" (gdb) x/6xb buf 0x7fffffffdf96: 0x61 0x62 0x63 0x64 0x65 0x00 (gdb) x/6c buf 0x7fffffffdf96: 97 'a' 98 'b' 99 'c' 100 'd' 101 'e' 0 '\000' (gdb) x/s buf 0x7fffffffdf96: "abcde" (gdb) n 23 printf("%s\n", buf); (gdb) x/6xb buf 0x7fffffffdf96: 0x61 0x62 0x63 0x64 0x65 0x00 (gdb) x/6c buf 0x7fffffffdf96: 97 'a' 98 'b' 99 'c' 100 'd' 101 'e' 0 '\000' (gdb) x/s buf 0x7fffffffdf96: "abcde" (gdb) c Continuing. abcde [Inferior 1 (process 9215) exited normally]
(gdb) x/6xb buf
0x7fffffffdf96: 0x61 0x62 0x63 0x64 0x65 0x00
6xbは、バイト単位で(b)、16進数で(x)、6単位表示するということ
(gdb) x/6c buf
0x7fffffffdf96: 97 'a' 98 'b' 99 'c' 100 'd' 101 'e' 0 '\000'
6cのcは文字で表示するということ
(gdb) x/s buf
0x7fffffffdf96: "abcde"
sは文字列で表示するということ