Right, I've got this code:
if(argc>1){
FILE * pFile = fopen(argv[1],"rb");
perror("");
}else{
FILE * pFile = fopen("hardcoded","rb");
}
if(pFile==NULL){
puts("Unable to open source file");
return -1;
}
However, I get this weird output:
Success
Unable to open source file
Weirdlier, if I do this:
if(argc>1){
FILE * pFile = fopen(argv[1],"rb");
perror("");
}else{
FILE * pFile = fopen("hardcoded","rb");
}
FILE * pFile = fopen("hardcoded","rb");
if(pFile==NULL){
puts("Unable to open source file");
return -1;
}
Where hardcoded exists, it all works fine!
What the blazes does that mea开发者_StackOverflow社区n?
Compiling with GCC4 on Ubuntu
I'm surprised your code compiles, since the you are declaring FILE *pFile
scoped to the if and the else blocks. If you've declare it prior to that, then remove the FILE*
text in front of the assignments in the if/else blocks.
Don't define pFile within the if
statement, you're losing scope.
FILE * pFile;
if(argc>1){
pFile = fopen(argv[1],"rb");
perror("");
}
I'd bet you've got a FILE * pfile;
earlier in your code that you didn't include. If it's outside all blocks, and has static storage duration, it's initialized to NULL.
When you then have FILE * pfile = fopen(...
in an inner block, the two pfile
s are two different things. Therefore, what's happening:
You're defining pfile
in a block, and opening it fine. Then you reach the end of the block, and it's being discarded like any other variable local in a block.
You're left with the original pfile
, which you never opened or assigned anything to, and that's likely to be NULL.
In the second case, you're opening a file and discarding it, and then you have a FILE * pfile
in the same scope as the testing if
statement, and that's the one you're testing, so it's fine.
What you need to do is define pfile
only once, since additional definitions will either cause compiler errors or give you separate versions. Take all the FILE *
out of your inner blocks, and just use the same pfile
all the time.
精彩评论