Reputation: 21
char fname[256];
printf("Enter file name\n");
scanf("%123s",fname);
strcat(fname,".txt");
FILE *inputf;
inputf=fopen(fname,"w");
if (inputf!=NULL)
printf("found");
else
printf("not found");
Mow the problem is that no matter what file name i enter i get a non null pointer.can any one explain why??
Upvotes: 0
Views: 2476
Reputation: 8694
Not this:
char fname[256];
printf("Enter file name\n");
scanf("%123s",fname);
strcat(fname,".txt"); F
FILE *inputf; inputf=fopen(fname,"w"); // <--!!!
if (inputf!=NULL) printf("found");
else printf("not found");
but this instead:
char fname[256]; FILE *inputf;
inputf=fopen(fname,"w");
printf("Enter file name\n");
// you know that you can't ever, EVER use scanf( ) so // remove this time bomb and use something else scanf("%123s",fname);
strcat(fname,".txt"); inputf=fopen(fname,"w"); if (inputf!=NULL) { printf("found"); } else { printf("not found"); }
Now, what pointer was not NULL? You could not have compiled the code as you had it, so how do you know what was or was not NULL?
--pete
Upvotes: 0
Reputation: 12570
fopen(filename,"w") will create a new file. Therefore, if you're entering a legal file name and have proper file system permissions, it should succeed.
If you're trying to open an existing file, use:
fopen(filename, "r")
(Notice the "r" mode, instead of "w".)
Upvotes: 3