1
0

cat_noblock.c 1.7 KB

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