#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/uio.h>
#include <unistd.h>
int main(void) {
int fd;
ssize_t cc;
char buf[2];
if ((fd = open("abc.txt", O_RDONLY)) == -1) {
perror("open");
exit(1);
}
while ((cc = read(fd, buf, sizeof(buf))) > 0) {
printf("%d bytes read\n", (int)cc);
}
if (cc == -1) {
perror("read");
exit(1);
}
if (close(fd) == -1) {
perror("close");
exit(1);
}
return 0;
}
$ cat abc.txt
abc
$ od -tx1 abc.txt
0000000 61 62 63 0a
0000004
GDBでデバッグした
(gdb) b main
(gdb) r
(gdb) n
19 while ((cc = read(fd, buf, sizeof(buf))) > 0) {
(gdb) p fd
$1 = 3
(gdb) n
21 printf("%d bytes read\n", (int)cc);
(gdb) p cc
$2 = 2
(gdb) p buf
$3 = "ab"
(gdb) n
2 bytes read
19 while ((cc = read(fd, buf, sizeof(buf))) > 0) {
(gdb)
21 printf("%d bytes read\n", (int)cc);
(gdb) p cc
$4 = 2
(gdb) p buf
$5 = "c\n"
(gdb) n
2 bytes read
19 while ((cc = read(fd, buf, sizeof(buf))) > 0) {
(gdb)
23 if (cc == -1) {
(gdb) p cc
$6 = 0
(gdb) p buf
$7 = "c\n"
(gdb) c
Continuing.
[Inferior 1 (process 24680) exited normally]