From 5c824ec1c7c49cbd3ec0fbf0c20a447560afcb5e Mon Sep 17 00:00:00 2001
From: Toby Murray <toby.murray@unimelb.edu.au>
Date: Fri, 6 Sep 2019 16:03:54 +1000
Subject: [PATCH] take input file on command line including - for stdin
---
src/passbook.c | 36 ++++++++++++++++++++++++++++++++----
1 file changed, 32 insertions(+), 4 deletions(-)
diff --git a/src/passbook.c b/src/passbook.c
index 49df7ae..a4e8438 100644
--- a/src/passbook.c
+++ b/src/passbook.c
@@ -365,7 +365,7 @@ void node_save(const node_t *p, FILE *f){
int save_levelorder(const node_t *p, const char * filename){
FILE *f = fopen(filename,"w");
if (f == NULL){
- debug_printf("Couldn't open file %s for writing.\n",filename);
+ fprintf(stderr,"Couldn't open file %s for writing.\n",filename);
return -1;
}
nodeptr_list_t lst = {.head = NULL, .last = NULL};
@@ -450,6 +450,8 @@ static int execute(void){
return 0;
}
+/* returns >=0 on success, in which case the number of instructions executed
+ is returned. Returns < 0 on failure. */
static int run(FILE *f){
debug_printf("Attempting to read program. max line length: %d\n",MAX_LINE_LENGTH);
@@ -492,7 +494,7 @@ static int run(FILE *f){
instructionCount++;
int r = execute();
if (r != 0){
- return r;
+ return -1;
}
}
@@ -528,7 +530,7 @@ static int run(FILE *f){
}
-int main(void){
+int main(const int argc, const char * argv[]){
cred_t cred1, cred2;
cred1.password = "asdfa";
cred1.username = "user1";
@@ -544,6 +546,32 @@ int main(void){
p = put(p,"http://blah.com",cred2);
assert(strcmp(lookup(p,"http://blah.com")->cred.username,cred2.username) == 0);
- run(stdin);
+ if (argc <= 1){
+ fprintf(stderr,"Usage: %s file1 file2 ...\n",argv[0]);
+ fprintf(stderr," use - to read from standard input\n");
+ exit(0);
+ }
+
+ for (int i = 1; i<argc; i++){
+ FILE *f;
+ if (strcmp(argv[i],"-") == 0){
+ f = stdin;
+ }else{
+ f = fopen(argv[i],"r");
+ if (f == NULL){
+ fprintf(stderr,"Error opening %s for reading\n",argv[i]);
+ exit(1);
+ }
+ }
+ int ans = run(f);
+ if (ans < 0){
+ fprintf(stderr,"Error\n");
+ exit(1);
+ }
+ /* do not close stdin */
+ if (f != stdin){
+ fclose(f);
+ }
+ }
return 0;
}
--
GitLab