Home > OS >  Opening a file with a string
Opening a file with a string

Time:12-11

I'm working on a problem that requires me to adjust the name of a file and then create a new file using the adjusted name. I'm storing the adjusted name in an array called nameHolder[]. I'd like to use nameHolder, which contains "file.txt" as the name of the new file. The code I have is the following:

void createNewFile(char nameHolder[])
{
    
    FILE* myNewFile = fopen(nameHolder, "r");

    fprintf("****************%s******************", nameHolder);

    fclose(myNewFile);
}

I get NULL for myNewFile and I believe this is due to "file.txt" not existing in the directory, but the problem requires that I create an entirely new file that doesn't already exist.

CodePudding user response:

You create a file, truncate it present like this:

FILE *myNewFile = fopen(nameHolder, "w");

Otherwise you want the mode "a" (or "a ").

CodePudding user response:

From the man page:

RETURN VALUE

Upon successful completion fopen(), fdopen(), and freopen() return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.

For a file to be read, it should exist, which doesn't in your case. fopen returns NULL on failure, you should check for it.

Unrelated:

The prototype of fprintf is:

int fprintf(FILE *restrict stream, const char *restrict format, ...);

The first argument should be a FILE *, remedy it.

  •  Tags:  
  • c
  • Related