home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / TEXTMOD.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  107 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  TEXTMOD.C - Demonstrates techniques for modifying text files
  5. **
  6. **  public domain demo by Bob Stout
  7. */
  8.  
  9. #include <string.h>
  10. #include "snipfile.h"
  11.  
  12. void show_text_file(char *txt)
  13. {
  14.       FILE *in;
  15.       char line[80];
  16.  
  17.       in = cant("test.txt", "r");
  18.       printf("\n%s:\n\n", txt);
  19.  
  20.       while (!feof(in))
  21.       {
  22.             if (NULL != fgets(line, 80, in))
  23.                   fputs(line, stdout);
  24.       }
  25. }
  26.  
  27. void create_text_file(void)
  28. {
  29.       FILE *out;
  30.  
  31.       out = cant("test.txt", "w");
  32.       fputs("This is a test!\n", out);
  33.       fputs("This is a dummy line to delete...\n", out);
  34.       fputs("This is a dummy line to modify...\n", out);
  35.       fputs("All done!\n", out);
  36.       fclose(out);
  37.  
  38.       show_text_file("The file as written is");
  39. }
  40.  
  41. main()
  42. {
  43.       FILE *in, *out;
  44.       char line[80], *tmp, *ptr;
  45.  
  46.       /*
  47.       **  Open the original file for reading and a temporary file for writing
  48.       */
  49.  
  50.       create_text_file();
  51.       in  = cant("test.txt", "r");
  52.       tmp = tmpnam(NULL);
  53.       out = cant(tmp, "w");
  54.  
  55.       /*
  56.       **  Read the first line and copy it
  57.       */
  58.  
  59.       fgets(line, 80, in);
  60.       fputs(line, out);
  61.  
  62.       /*
  63.       **  Discard the second line
  64.       */
  65.  
  66.       fgets(line, 80, in);
  67.  
  68.       /*
  69.       **  Add a new line
  70.       */
  71.  
  72.       fputs("(Isn't it?)\n", out);
  73.  
  74.       /*
  75.       **  Read the 3rd line, modify it, then write it out
  76.       */
  77.  
  78.       fgets(line, 80, in);
  79.       ptr = strrchr(line, 'm');
  80.       strcpy(ptr, "edit...\n");
  81.       fputs(line, out);
  82.  
  83.       /*
  84.       **  Read the last line and copy it
  85.       */
  86.  
  87.       fgets(line, 80, in);
  88.       fputs(line, out);
  89.  
  90.       /*
  91.       **  Close the files, delete the old, rename the temp
  92.       */
  93.  
  94.       fclose(in);
  95.       fclose(out);
  96.       remove("test.txt");
  97.       rename(tmp, "test.txt");
  98.  
  99.       /*
  100.       **  Now let's see the results
  101.       */
  102.  
  103.       show_text_file("The file as modified is");
  104.       
  105.       return 0;
  106. }
  107.