fopen failed with my file path

Jazz R Source

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.

cfopen

Answers

answered 3 months ago Abhijit Pritam #1

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");

answered 3 months ago Tom's #2

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);
}

comments powered by Disqus