-1

The file is created, but the function WriteFile can't write in the file, I need to create the file in a function not in the main.

    #include <stdio.h>
    #include <stdlib.h>

    void CreateFile(FILE *file){
        file = fopen("file.txt","w");
        if(file == NULL){
            printf("Error : Could not create the file");
        }
    }
   void WriteFile(FILE *file){
        fprintf(file,"Hello !");
    }

    int main()
    {
        FILE *file = NULL;
        CreateFile(file);
        WriteFile(file);
        fclose(file);
        return 0;
    }
Goun2
  • 417
  • 1
  • 11
  • 22

2 Answers2

0

As mentioned by Eugene Sh, you don't keep the pointer to the file you create. This fixes it:

#include <stdio.h>
#include <stdlib.h>

FILE *CreateFile(void){
    FILE *file = fopen("file.txt","w");
    if(file == NULL){
        printf("Error : Could not create the file");
        exit(1);
    }
    return file;
}

void WriteFile(FILE *file){
    fprintf(file, "Hello !");
}

int main(void)
{
    FILE *file = CreateFile();
    WriteFile(file);
    fclose(file);
    return 0;
}

Or, if you want to send the variable file from main into the function, use a double pointer:

#include <stdio.h>
#include <stdlib.h>

void CreateFile(FILE **file){
    *file = fopen("file.txt","w");
    if(*file == NULL){
        printf("Error : Could not create the file");
    }
}

void WriteFile(FILE *file){
    fprintf(file, "Hello !");
}

int main(void)
{
    FILE *file = NULL;
    CreateFile(&file);
    WriteFile(file);
    fclose(file);
    return 0;
}
0

The problem is not the file, it's your use of the pointers. In C, function parameters are passed by value : It means that in your code when you call CreateFile(file); you are giving the value of file, which is NULL. You have two possibilities to fix this, you can use a double pointer :

void CreateFile(FILE **file);

Calling the function like this :

FILE *file;
CreateFile(&file);

Or you can return the value from CreateFile() :

FILE *CreateFile(void);
FILE *file = CreateFile();

(Edit : I did not see @Hans Petter Taugbøl Kragset's answer ...)

Gam
  • 684
  • 1
  • 8
  • 17