cat_noblock.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * cat_noblock.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(-1);
  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. if (errno = EAGAIN)
  27. puts("Open would block");
  28. else
  29. puts("Open failed");
  30. exit(-1);
  31. }
  32. /* Read the file and output its contents */
  33. do {
  34. int i;
  35. /* Read characters from the file */
  36. bytes = read(fd, buffer, MAX_BYTES);
  37. /* If there's an error, report it and die */
  38. if (bytes == -1) {
  39. if (errno = EAGAIN)
  40. puts("Normally I'd block, but you told me not to");
  41. else
  42. puts("Another read error");
  43. exit(-1);
  44. }
  45. /* Print the characters */
  46. if (bytes > 0) {
  47. for (i = 0; i < bytes; i++)
  48. putchar(buffer[i]);
  49. }
  50. /* While there are no errors and the file isn't over */
  51. } while (bytes > 0);
  52. return 0;
  53. }