Originally Posted by
bigmac(rexdale)
oh i see, so i should put return fp; to end it
...Yes, assuming you want to return the file pointer to the calling function. Which I think is what you need to do here. Right now with your code, all you're doing is returning null.
Though if you're just closing the file anyway in your function, returning fp won't do a lot of good because it's a null pointer and if anyone tries to use it their application will likely crash.
Edit: Let me explain, using your code.
Code:
#include <cstdio> // stdio.h, for file access.
/* This is a function declaration. What this means is that this line
declares a function (called open, that takes a const char[] called filename
as an argument) that will be defined later in code. */
FILE* open(const char filename[]);
int main() {
const char filename[100] = "prefix.dat"; // Why are you allocating a string like this? Try const char* filename.
open(filename);
}
// Here's your function defination. This defines the function you declared before main().
FILE* open(const char filename[]) {
FILE* fp; // Create a FILE* called fp.
char c[10];
printf(filename);
fp = fopen(filename, "r"); // Try to open the file, and return the file handle to your FILE* called fp.
if (fp == NULL) { // If fopen() fails, fp is NULL...
printf(" cannot open");
}
else { // ...else it succeeded and fp is valid.
printf(" opened");
fscanf(fp, "%s", c);
printf("%s", c);
/* Why are you closing your file handle? This invalidates fp, and there's no reason
to return a FILE* from open() if you do this. It will always be NULL. */
fclose(fp);
// You can return() fp here, or...
}
// ...here, but ONLY if you keep fp valid and don't use fclose().
}