Reputation: 15
I could be doing this completely the wrong way, but considering this will be for personal use, having it not be that efficient is okay.
When ran as ./todo -r
, it works.
When ran as ./todo -a
, it works.
When ran as ./todo
, it gives me segmentation fault (core dumped)
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[]) {
if(argc < 1) {
printf("Not enough variables.");
}
if(strcmp("-r",argv[1])==0) {
printf("\n");
system("cat .todo");
printf("\n");
}
if(strcmp("-a",argv[1])==0) {
char str[BUFSIZ];
FILE *f;
f = fopen(".todo","a");
printf("\n\nTODO list\n\n");
for(;;) {
printf("~ ");
fgets(str,256,stdin);
if(strcmp(str,"\n")==0) {
fclose(f);
printf("\n");
break;
}
fprintf(f,str);
}
return 0;
}
}
Upvotes: 0
Views: 998
Reputation: 68033
argv[0]
is the program executable name, and it's counted towards argc
.
So ./todo
has argc=1
, but argv[1]
is NULL, which will cause a problem for strcmp()
.
See argv[argc] ==?
Change your test:-
if (argc < 2)
{
printf("Not enough variables.");
return 0; // do this, otherwise we'll plough straight on..
}
Upvotes: 2
Reputation: 19339
As others have pointed out, you need argc < 2
rather than argc < 1
.
Additionally, you probably want to return from the if
, to stop the rest from executing:
if(argc < 2) {
printf("Not enough variables.");
return /* some appropriate value here */;
}
Upvotes: 1
Reputation: 360602
You're closing your file handle and then still trying to write to it:
if (...) {
fclose(...); <--potentially closing it, depending on the if() results
}
fprintf(...); <--potentially writing to a closed handle.
This is a BAD idea.
Upvotes: 0