ronek22
ronek22

Reputation: 148

readFile function without fclose

I have a function to add new words to a .txt file. I still have to make a function to learn the vocabulary. Several times I have to read the file, so I try to make a function for it.

void readFile(FILE* fp, char *name){
  if((fp=fopen(name,"a"))==NULL) {
    printf("I cannot open file!\n");
    exit(1);
  }
}

And I don't want to close the file in this function, because in other functions I would operate on this file.

int main(){
  FILE *file;
  readFile(file,"verbs.txt");
  fclose(file);

  return 0;
}

If I try to close file like that, I get core dump. But if fclose is in a readFile it works well. So it is possible to write readFile function without fclose()?

Upvotes: 1

Views: 175

Answers (3)

Steve Summit
Steve Summit

Reputation: 47962

If you want the readFile function to manage its own file pointer, I would do it more like this:

static FILE *fp = NULL;

void readFile(char *name){
  if((fp=fopen(name,"a"))==NULL) {
    printf("I cannot open file!\n");
    exit(1);
  }
}

void closeFile(){
  if(fp!=NULL) {
    fclose(fp);
    fp = NULL;
  }
}

Upvotes: 0

dbush
dbush

Reputation: 224082

All parameters in C are pass by value. Changing the value of fp in your function does not change the value in the calling function.

You can return the value and use that instead:

FILE *readFile(char *name){
  FILE *fp;
  if((fp=fopen(name,"a"))==NULL) {
    printf("I cannot open file!\n");
    exit(1);
  }
  return fp;
}

int main(){
  FILE *file = readFile("verbs.txt");
  fclose(file);

  return 0;
}

Upvotes: 1

phoenix
phoenix

Reputation: 3159

Change it to:

void readFile(FILE** fp, char *name){
  if((*fp=fopen(name,"a"))==NULL) {
    printf("I cannot open file!\n");
    exit(1);
  }
}

int main(){
  FILE *file=NULL;
  readFile(&file,"verbs.txt");
  //Use the file here after checking for NULL. 
  if (file != NULL)
      fclose(file); //check for NULL before closing.

  return 0;
}

Upvotes: 2

Related Questions