Advertisement
Guest User

hi

a guest
Apr 26th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <fcntl.h>
  5. #include <errno.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <stdint.h>
  9. int main(int argc, char **argv)
  10. {
  11. int fd;
  12. ssize_t bytesRead;
  13. uint8_t buf[1024];
  14. size_t count[sizeof(buf)];
  15. int closed;
  16. ssize_t written;
  17.  
  18. if(argc == 1 ) //no arguments ->read from stdin and write to stdout
  19. {
  20. while(read(STDIN_FILENO, buf, 1) != 0)
  21. {
  22. write(STDOUT_FILENO, buf, 1);
  23. }
  24. exit(0);
  25. }
  26. else
  27. {
  28. for (int i = 1; i < argc; ++i) //for each argument:
  29. {
  30. fd = open(argv[i], O_RDONLY); //open file
  31. if (fd == -1) //check error
  32. {
  33. perror(argv[i]);
  34. exit(errno);
  35. }
  36. else
  37. {
  38. while((bytesRead = read(fd, buf, *buf)) != 0) //read file to the end "0"
  39. {
  40. if(bytesRead == -1) //error checking
  41. {
  42. perror(argv[i]);
  43. exit(errno);
  44. }
  45. else
  46. {
  47. count[i] = bytesRead; //count number of bytes in file
  48. written = write(STDOUT_FILENO, buf, count[i]); //print out file contents
  49. if(written == -1) //error checking
  50. {
  51. perror(argv[i]);
  52. exit(errno);
  53. }
  54. }
  55.  
  56. }
  57.  
  58. }
  59. closed = close(fd); //close file descriptor
  60. if(closed == -1)
  61. {
  62. perror(argv[i]);
  63. exit(errno);
  64. }
  65. }
  66. }
  67.  
  68. return 0;
  69. }
  70. 69,1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement