Day 16/100 Split Cat
Cats are liquid, definitely!
So, I wrote a cat program. For those of you who don't know, "cat" is short for "concatenate", which is a way of saying that you will just jumble everything together. This is such a program. I simply adapted the last program, which was FileGlob, to this one, although I end up deleting most of it, anyway.
So, this is the result:
for (int i=1;i<argc;i++) {if (!strcmp(argv[i],"-")) ifp=stdin;else if ((ifp=fopen(argv[i],"r"))==NULL) {puts("File open Error"); return 1;}while (lptr=fgets(Data,MAXSTR,ifp))ProcessData();if (ifp!=stdin) fclose(ifp);}
But it's so easy! Therefore, I added a special option: Split. Actually, this is closer to csplit, which split a file separated by a particular regex. I decided to just split it with a particular file name:
void ProcessData() {if (sscanf(Data,"WRITE FILE %s",ofname)) {if (ofp) { fclose(ofp); ofp=NULL; }ofp=fopen(ofname,"w"); return;}printf("%s",Data);if (ofp) fprintf(ofp,"%s",Data);}
And, uh, that's it! Nothing to it. Too easy!
#include <stdio.h>#include <stdlib.h>#include <string.h>
#define MAXSTR 256char Data[MAXSTR];char ofname[MAXSTR];FILE *ifp;FILE *ofp=NULL;void ProcessData();
int Init() {return 0;}
int ReadData(int argc, char *argv[]) {char *lptr;for (int i=1;i<argc;i++) {if (!strcmp(argv[i],"-")) ifp=stdin;else if ((ifp=fopen(argv[i],"r"))==NULL) {puts("File open Error"); return 1;}while (lptr=fgets(Data,MAXSTR,ifp))ProcessData();if (ifp!=stdin) fclose(ifp);}return 0;}
void ProcessData() {if (sscanf(Data,"WRITE FILE %s",ofname)) {if (ofp) { fclose(ofp); ofp=NULL; }ofp=fopen(ofname,"w"); return;}printf("%s",Data);if (ofp) fprintf(ofp,"%s",Data);}
void CleanUp() {if (ofp) { fclose(ofp); ofp=NULL; }}
int main (int argc, char *argv[] ) {int e=0;if (argc<2) {puts("cat file1 file2 file3 ...");puts("\"WRITE FILE [filename]\" will write to said file");return 1;}Init(argc,argv);ReadData(argc,argv);CleanUp();return e;}
On that note: I did a function prototype declaration for ProcessData(). I could have just move it to the top, but I decided against it.
No comments:
Post a Comment