Jazz R
Jazz R

Reputation: 3

fopen failed with my file path

Trying to open and write to the following file path, for some reason it is not opening, I've tried several different paths and nothing has worked. I am running this from C:\

FILE* fptwo = fopen("\\C:\\Program Files\\NotMal.txt", "w");
if (fptwo != NULL)
{
    printf("open progfiles successful \n"); 
    //add this text to the file 
    fprintf(fptwo, "This is text");
    printf("add text succuessful \n");

    //close file pointer when finished
    fclose(fptwo);
}

*please feel free to delete or close this question if it is answered somewhere else, I apologize for the mistakes made within this, and if it is a stupid error.

Upvotes: 0

Views: 1979

Answers (2)

Tom's
Tom's

Reputation: 2506

You test if you have correctly opened the file, it's good ! But it's better to know why your function call have failed.

For "fopen", you can know by looking the value of errno. (read the man about fopen). And a "cool thing" is that you can obtain an english description by using "strerror".

So, just do :

#include <string.h> // For strerror
#include <errno.h> // For .... errno

FILE* fptwo = fopen("\\C:\\Program Files\\NotMal.txt", "w");
if (fptwo == NULL)
{
    printf("Error : errno='%s'.\n", strerror(errno));
}
else
{
    printf("open progfiles successful \n"); 
    //add this text to the file 
    fprintf(fptwo, "This is text");
    printf("add text succuessful \n");

    //close file pointer when finished
    fclose(fptwo);
}

Upvotes: 1

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5591

Program Files is windows default software deployment folder. Better not to use that path. Better create your own test folder and test. If possible not to name folder with space.

FILE* fptwo = fopen("C:\\MyProject\\test\\NotMal.txt", "w");

Upvotes: 0

Related Questions