Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <unistd.h>
  7.  
  8. int main(int argc, char *argv[]) {
  9. char* source;
  10. char* destination;
  11.  
  12. // take program arguments
  13. if (argc != 3) {
  14. printf("Bad call. Syntax: 'filtertouppercase source destination'\n");
  15. return 1;
  16. }
  17. else {
  18. source = argv[1];
  19. destination = argv[2];
  20. }
  21.  
  22. // open source
  23. int source_fd = open(source, O_RDONLY); // source file descriptor
  24. if (source_fd == -1) {
  25. printf("Error opening source file. Aborting...\n");
  26. return 2;
  27. }
  28.  
  29. // check for destination and confirm overwrite
  30. if (access(destination, R_OK) != -1) {
  31. printf("The output file already exists. Confirm overwrite? Y/N\n");
  32. char answer;
  33. scanf("%c", &answer);
  34. if (answer != 'Y') {
  35. printf("Could not write to destination file. Aborting...\n");
  36. return 4;
  37. }
  38. }
  39.  
  40. // open destination (create if it doesn't exist, wipe it if it does)
  41. int destination_fd = open(destination, O_WRONLY | O_CREAT | O_TRUNC);
  42. if (destination_fd == -1) {
  43. printf("Error opening destination file. Aborting...\n");
  44. return 5;
  45. }
  46.  
  47. // read text in 1KB chunks, convert them, and write them
  48. char chunk[1024];
  49. // first read
  50. int chunk_size = read(source_fd, chunk, 1024);
  51. if (chunk_size == -1) {
  52. printf("Error reading from source file. Aborting...\n");
  53. return 3;
  54. }
  55.  
  56. while (chunk_size > 0) {
  57. // conversion
  58. for (int i = 0; i < chunk_size; i++) {
  59. if (chunk[i] >= 'a' && chunk[i] <= 'z') {
  60. chunk[i] += 'A' - 'a';
  61. }
  62. }
  63. // writing
  64. write(destination_fd, chunk, chunk_size);
  65. // reading
  66. chunk_size = read(source_fd, chunk, 1024);
  67. }
  68.  
  69. // close files
  70. close(source_fd);
  71. close(destination_fd);
  72. printf("Program finished execution succesfully.\n");
  73.  
  74. return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement