Home > Back-end >  Check if a file exist
Check if a file exist

Time:11-15

How can I check if a file exists in APPDATA without using the full path ?

#include <stdio.h>
#include <unistd.h> 
#include <windows.h>

int main(void)
{
    if (access("%APPDATA%\\changzhi_leidianmac.data", F_OK) != -1)
    {
        printf("File Found......");
    }
    else
    {
        printf("File not found !!!!");
    }

    return 0;
}

CodePudding user response:

You can use getenv

#include <stdlib.h>

int main(void)
{
    char *appdata = getenv("APPDATA");
    ...
    ...
}

And later use snprintf.

CodePudding user response:

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

#include <unistd.h>


int main(void)
{
    //  Define the trailing portion of the file path.
    static const char FileName[] = "\\changzhi_leidianmac.data";

    //  Get the value of environment variable APPDATA or fail if it is not set.
    const char *APPDATA = getenv("APPDATA");
    if (!APPDATA)
    {
        fputs("Error, the environment variable APPDATA is not defined.\n",
            stderr);
        exit(EXIT_FAILURE);
    }
    printf("APPDATA is %s.\n", APPDATA);

    //  Figure the space needed.  (Note that FileName includes a null terminator.)
    size_t Size = strlen(APPDATA)   sizeof FileName;

    //  Get space for the full path.
    char *Path = malloc(Size);
    if (!Path)
    {
        fprintf(stderr,
            "Error, unable to allocate %zu bytes of memory for file path.\n",
            Size);
        exit(EXIT_FAILURE);
    }

    //  Copy APPDATA to the space for the path, then append FileName.
    strcpy(Path, APPDATA);
    strcat(Path, FileName);
    printf("Full file path is %s.\n", Path);

    //  Test whether the file exists and report.
    if (0 == access(Path, F_OK))
        puts("The file exists.");
    else
    {
        puts("The file does not exist.");
        perror("access");
    }
}

CodePudding user response:

C does not have any provisions for accessing env variables. You need to use either a library or system commands to get the data.

  • Related