home *** CD-ROM | disk | FTP | other *** search
- /*
- ** sed.c -- stream editor.
- ** Date: Wednesday, 21 January 1987. Time: 08:18:54.
- ** Roberto T. Edwards
- */
-
- #define LINT_ARGS
- #define EOS '\0';
-
- #include "stdio.h"
- #include "string.h"
- #include "dir.h"
- #include "dos.h"
-
- #define MAXSTR 256
-
- FILE *open_file();
- char *getfile();
- char buf1[MAXSTR],buf2[MAXSTR];
- int buf,oldlen,newlen;
-
- main(argc,argv)
- int argc;
- char **argv;
- {
- FILE *fp;
- char *name;
-
- if (argc != 4) {
- printf("usage: sed <file> <old_string> <new_string>\n");
- exit(1);
- }
- oldlen = strlen(argv[2]);
- newlen = strlen(argv[3]);
- while (name = getfile(argv[1])) {
- fp = open_file(name,"r");
- printf("\n/* %s */\n\n",name);
- while (fgets(buf1,MAXSTR-1,fp)) {
- buf = 1;
- replace(buf1,argv[2],argv[3]);
- printf("%s",buf == 1 ? buf1:buf2);
- }
- fclose (fp);
- }
- }
-
- /*
- ** open_file -- open a stream and check for errors.
- */
-
- FILE *open_file(name,mode)
- char *name,*mode;
- {
- FILE *fp;
-
- fp = fopen(name,mode);
- if (fp == NULL) {
- printf("error: can't open %s",name);
- exit(1);
- }
- return(fp);
- }
-
- /*
- ** replace -- replace all occurrences of oldstr with newstr in buffer
- */
-
- replace(buffer,oldstr,newstr)
- char *buffer,*oldstr,*newstr;
- {
- char *osp,*b1p,*b2p;
-
- if ((osp=strstr(buffer,oldstr)) == NULL)
- return;
- b1p = buf1;
- b2p = buf2;
- if (buf == 1) {
- while (b1p != osp)
- *b2p++ = *b1p++;
- while (*newstr)
- *b2p++ = *newstr++;
- b1p += oldlen;
- while (*b1p)
- *b2p++ = *b1p++;
- *b2p = EOS;
- buf = 2;
- replace(buf2,oldstr,newstr-newlen);
- }
- else {
- while (b2p != osp)
- *b1p++ = *b2p++;
- while (*newstr)
- *b1p++ = *newstr++;
- b2p += oldlen;
- while (*b2p)
- *b1p++ = *b2p++;
- *b1p = EOS;
- buf = 1;
- replace(buf1,oldstr,newstr-newlen);
- }
- }
-
- char *getfile(arg)
- char *arg;
- {
- static struct ffblk filblk;
- static flag = 0;
- static struct LLIST {
- char *fname;
- struct LLIST *next;
- } *head,*current;
- char *retval;
-
- if (flag == 0) {
- if (findfirst(arg,&filblk,0))
- return(NULL);
- head = current = (struct LLIST *) malloc(sizeof(struct LLIST));
- current->fname = strdup(filblk.ff_name);
- current->next = NULL;
- while (findnext(&filblk) == 0) {
- current->next = (struct LLIST *) malloc(sizeof(struct LLIST));
- current = current->next;
- current->fname = strdup(filblk.ff_name);
- current->next = NULL;
- }
- current = head;
- flag = 1;
- }
- retval = current->fname;
- current = current->next;
- return(retval);
- }