file_reader.c 816 B

123456789101112131415161718192021222324252627282930
  1. #include <stdio.h> // printf() 函数的定义
  2. #include <fcntl.h> // O_RDONLY 的定义
  3. #include <stdlib.h> // exit() 函数的定义
  4. #include <unistd.h> // read(), close() 函数在 unistd.h 定义的(unix standard)
  5. #include <string.h> // memset() 函数的定义
  6. int main(int argc, char** argv){
  7. int fd;
  8. char *filename = "/tmp/file";
  9. fd = open(filename, O_RDONLY);
  10. if(fd == -1){
  11. fprintf(stderr, "Cannot open /tmp/file.\n");
  12. exit(1);
  13. }
  14. char buf[20];
  15. size_t nbytes;
  16. size_t bytes_read, total_bytes_read = 0;
  17. nbytes = sizeof(buf);
  18. while((bytes_read = read(fd, buf, nbytes)) >0){
  19. total_bytes_read += bytes_read;
  20. fwrite(buf, sizeof(char), bytes_read, stdout);
  21. memset(buf, 0, sizeof buf);
  22. }
  23. printf("bytes read:%zd ", total_bytes_read);
  24. close(fd);
  25. return 0;
  26. }