1
0

reducto.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // reducto.c -- reduces your files by two-thirds!
  2. #include <stdio.h>
  3. #include <stdlib.h> // for exit()
  4. #include <string.h> // for strcpy(), strcat()
  5. #define LEN 40
  6. int main(int argc, char *argv[])
  7. {
  8. FILE *in, *out; // declare two FILE pointers
  9. int ch;
  10. char name[LEN]; // storage for output filename
  11. int count = 0;
  12. // check for command-line arguments
  13. if (argc < 2)
  14. {
  15. fprintf(stderr, "Usage: %s filename\n", argv[0]);
  16. exit(EXIT_FAILURE);
  17. }
  18. // set up input
  19. if ((in = fopen(argv[1], "r")) == NULL)
  20. {
  21. fprintf(stderr, "I couldn't open the file \"%s\"\n",
  22. argv[1]);
  23. exit(EXIT_FAILURE);
  24. }
  25. // set up output
  26. strncpy(name,argv[1], LEN - 5); // copy filename
  27. name[LEN - 5] = '\0';
  28. strcat(name,".red"); // append .red
  29. if ((out = fopen(name, "w")) == NULL)
  30. { // open file for writing
  31. fprintf(stderr,"Can't create output file.\n");
  32. exit(3);
  33. }
  34. // copy data
  35. while ((ch = getc(in)) != EOF)
  36. if (count++ % 3 == 0)
  37. putc(ch, out); // print every 3rd char
  38. // clean up
  39. if (fclose(in) != 0 || fclose(out) != 0)
  40. fprintf(stderr,"Error in closing files\n");
  41. return 0;
  42. }