I've started to get comfortable with getopt() and how to use it. Right now I'm making a cat clone, camt, to teach myself some things, between them setting flags in execution.
My solution was to set global variable in my camt.h and to change them based on the flags I want to set. It looks something like this:
The code in camt.c is:
bool line_numbers = false;
int main(int argc, char *argv[]){
int opt = 0;
while((opt = getopt(argc, argv, "n")) != -1){
switch(opt){
case 'n':
line_numbers = true;
break;
default:
break;
}
}
int ch;
FILE* foofile;
int o_files = 1;
do{
//read file
foofile = fopen(argv[o_files], "r");
if(line_numbers){
display_ln(foofile); //line-numbers
}else{
display(foofile); /"normal" cat
}
fclose(foofile);
o_files++;
}while(o_files < argc);
printf("\n"); //final scape character for nice prompt
return(EXIT_SUCCESS);
}
Btw, I'd be surprised if there wasn't a better, less utterly horrendous method to set flags in a program, in which case I'd be grateful if you told it to me :) Please take into consideration that I'm a beginner that can barely clone a repository with git, so please be nice.
Thanks.
Jesus, that was a dumb fix. I wasn't having issues reading my global variable, but opening the file.
The problem was that I defaulted the o_files
, which is what I use to know what file I'm reading, to 1. This wasn't a problem when the first argument was a file or I set a flag which ended the program immediatly, but it was when I gave an option and ran the entire program.
I was always defaulting the first argument as if it were a file; the program activated the p_flags.line_numbers
flag correctly and then tried to read -n
, argument 1, as if it were a file, which obviously didn't exist.
TL;DR: Pretty much, I was reading all my arguments as files and then tried to open them, this isn't a problem when all arguments are files, but it is when not all of them are.