-
Opening a file
I am having trouble opening file.
[code]
// when file location is passed as an argument on command line
/(1)
FILE *fp;
fp = fopen(argv[2],"r");
// where argv[2] holds the file location
// this operation works for me
BUT
//(2)
FILE *fp;
char *filename;
filename="dic.f" // where dic.f is an actual file with correct permissions
fp=fopen(filename,"r");
//my problem is that fp==NULL, even though when i put 'dic.f' in (1) it works fine.
[code]
Where is my problem??
-
are both versions being run in the same directory? Try a couple things. First, try to put "dic.f" in the fopen() call instead of the filename variable. Next try to see if you put the full path to dic.f in if that makes a difference.
-
Is that how the code actually looks in your program? (You are missing the semi-colon). Perhaps you could post a little more code so we can have a better idea of what is happening.
~/
-
Please excuse me if any of these make you feel ignorant, I'm sure you checked for them, as you put "actual file with correct permissions", but be sure that all the following are true.
If FOPEN is returning null, make sure of the following:
Your file is in the same directory as the program (even if it is, try putting the full path name in the variable)
Your file contains nothing more than a standard text file would contain. No fancy symbols or fonts, etc.
Your file isn't write protected (I'd assume you checked this)
Also, I'd say that if the first code you posted using the command line arguement to pass the file name, then did you try passing "dic.f" through that code? Does it work?
Again, if you did do all these things, I wouldn't be suprised, I'm just posting them because sometimes basic things slip people's mind.
-
After fopen returns NULL, check errno, and output the error with strerror(errno).
-
And once you're finished with a file, you should close it with fclose():
Code:
fclose(file_pointer);