cat_noblock.c 1.7 KB

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