home *** CD-ROM | disk | FTP | other *** search
/ Simtel MSDOS - Coast to Coast / simteldosarchivecoasttocoast.iso / pcmag / vol8n05.zip / NUMB2.C < prev    next >
C/C++ Source or Header  |  1988-12-12  |  2KB  |  60 lines

  1. /*  NUMB2.C:    Utility to number the lines in a file, 
  2.                 using the C "stream" file functions.
  3.     Copyright (c) 1989 Ziff Communications Co.
  4.     PC Magazine * Ray Duncan
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <string.h>
  9.  
  10. FILE *ifile;                        /* input file */    
  11. FILE *ofile;                        /* output file */
  12.  
  13. char fbuff[256];                    /* file I/O buffer */
  14. char iname[80];                     /* name of input file */
  15. char oname[80];                     /* name of output file */
  16.  
  17. main(int argc, char *argv[])
  18. {
  19.     char *p;                        /* scratch pointer */
  20.     int line = 1;                   /* line number */
  21.  
  22.     if(argc < 2)                    /* make sure filename present */
  23.     {
  24.         fprintf(stderr,"\nnumb2: missing filename\n");
  25.         exit(1);
  26.     }
  27.  
  28.     strcpy(iname, argv[1]);         /* get input filename */
  29.     strcpy(oname, argv[1]);         /* build output filename */
  30.     if(! (p = strchr(oname, '.')))  /* point to extension */
  31.         p = strchr(oname, '\0');
  32.  
  33.     strcpy(p, ".$$$");              /* temp. name for new file */
  34.  
  35.     ifile = fopen(iname, "r");      /* open input file */
  36.     ofile = fopen(oname, "w");      /* create output file */
  37.  
  38.     if((ifile == NULL) || (ofile == NULL))
  39.     {
  40.         fprintf(stderr,"\nnumb2: open or create error\n");
  41.         exit(1);
  42.     }
  43.  
  44.     while(fgets(fbuff, 256, ifile) != NULL)
  45.     {                               /* read until end of file */
  46.                                     /* write line number */
  47.         fprintf(ofile, "%04d\t", line++);
  48.         fputs(fbuff,ofile);         /* write line text */
  49.     }
  50.  
  51.     fclose(ifile);                  /* close input file */
  52.     fclose(ofile);                  /* close output file */
  53.  
  54.     strcpy(p, ".bak");              /* build .BAK filename */
  55.     unlink(oname);                  /* delete previous .BAK file */
  56.     rename(iname, oname);           /* make original file .BAK */
  57.     strcpy(p, ".$$$");              /* give new file same name */
  58.     rename(oname, iname);           /* as original file */
  59. }
  60.