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;
  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) {
    /* ccに読んだバイト数、bufに読んだデータが入る */
    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]