Reputation: 162
I'm trying to do basic file I/O error handling in C, but for some reason my code doesn't exit immediately when it runs exit(), but continues the rest of the code and segfaulting.
I've commented the line where it should exit. Why isn't my program exiting here?
given command: (use this)
./test
correct command:
./test <Input file>
The code is supposed to check for an additional keyword argument, and if it doesn't it raises an error.
int main(int argc, char* argv[]){
FILE *fp;
int cur;
printf("%i", argc);
if (argc < 1){
perror("Syntax: ./test <Input File>");
exit(1);
}
// validate in_args are READABLE
for (int i=1; i<argc; i++){
fp = fopen(argv[i],"r");
if (fp == NULL){
fprintf(stderr, "%s: cannot open %s", argv[0], argv[i]);
exit(1);
}
}
// ================================ ^should exit here
// OPEN FILE - EXCEPTIONS
fp = fopen(argv[1], "r");
while ((cur=fgetc(fp))!=EOF){
printf("%c",cur);
}
if (fp){
fclose(fp);
}
}
Upvotes: 0
Views: 93
Reputation: 39
I am not exactly sure about your answer, but I have a solution which may work
Instead of using exit(1), Use break And after loop put (exit(1))
for (int i = 0; i < 100; ++i) { if (condition) exit(1); //what you are doing }
Now see what you can do to solve your problem
for (int i = 0; i < 100; ++i) { If (condition) break; } exit(1);
Upvotes: 0
Reputation: 126203
This test
if (argc < 1) {
will never be true -- there will always be at least one argument (the program name). You probably want
if (argc != 2) {
here, requiring the program be run with exactly two arguments, the program name (argc[0]) and the input file (argc[1])
Upvotes: 1
Reputation: 162
Nevermind...forgot input arguments started from argv[1...argc] onwards
Upvotes: 0