cat_nonblock.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * cat_nonblock.c - open a file and display its contents, but exit rather than
  3. * wait for input.
  4. */
  5. #include <errno.h> /* for errno */
  6. #include <fcntl.h> /* for open */
  7. #include <stdio.h> /* standard I/O */
  8. #include <stdlib.h> /* for exit */
  9. #include <unistd.h> /* for read */
  10. #define MAX_BYTES 1024 * 4
  11. int main(int argc, char *argv[])
  12. {
  13. int fd; /* The file descriptor for the file to read */
  14. size_t bytes; /* The number of bytes read */
  15. char buffer[MAX_BYTES]; /* The buffer for the bytes */
  16. /* Usage */
  17. if (argc != 2) {
  18. printf("Usage: %s <filename>\n", argv[0]);
  19. puts("Reads the content of a file, but doesn't wait for input");
  20. exit(EXIT_FAILURE);
  21. }
  22. /* Open the file for reading in non blocking mode */
  23. fd = open(argv[1], O_RDONLY | O_NONBLOCK);
  24. /* If open failed */
  25. if (fd == -1) {
  26. puts(errno == EAGAIN ? "Open would block" : "Open failed");
  27. exit(EXIT_FAILURE);
  28. }
  29. /* Read the file and output its contents */
  30. do {
  31. /* Read characters from the file */
  32. bytes = read(fd, buffer, MAX_BYTES);
  33. /* If there's an error, report it and die */
  34. if (bytes == -1) {
  35. if (errno == EAGAIN)
  36. puts("Normally I'd block, but you told me not to");
  37. else
  38. puts("Another read error");
  39. exit(EXIT_FAILURE);
  40. }
  41. /* Print the characters */
  42. if (bytes > 0) {
  43. for (int i = 0; i < bytes; i++)
  44. putchar(buffer[i]);
  45. }
  46. /* While there are no errors and the file isn't over */
  47. } while (bytes > 0);
  48. close(fd);
  49. return 0;
  50. }