Check if file existing or not in c

327 views Asked by At
  1. prgchDirPath is char pointer. But expected is LPCWSTR. How to change this?
  2. prgchDirPath is a directory path. File is not existed. But I want to make sure if directory/path exists or not. Can the API below helps me? if yes, how?

    unsigned char IsFilePathCorrect(char* prgchDirPath)
    {
            WIN32_FIND_DATA FindFileData;
            HANDLE handle;
            int found=0;
    
            //1. prgchDirPath is char pointer. But expected is LPCWSTR.
            //How to change this?
            //2. prgchDirPath is a directory path. File is not existed.
            //But I want to make sure if directory/path exists or not.
            //Can the API below helps me? if yes, how?
            handle = FindFirstFile(prgchDirPath, &FindFileData);
            if(handle != INVALID_HANDLE_VALUE)
            found = 1;
            if(found) 
            {
                FindClose(handle);
            }
            return found;
    }
    

I want to check if directory path is existed or not. Please provide one sample code. Thank you.

4

There are 4 answers

0
Megharaj On
#include<stdio.h>
#include<fcntl.h>

#define DEVICE "test.txt"

int main()
{
    int value = 0;
    if(access(DEVICE, F_OK) == -1) {
        printf("file %s not present\n",DEVICE);
        return 0;
    }
    else
        printf("file %s present, will be used\n",DEVICE);
    return 0;
}
0
Rahul Tripathi On

How about doing it like this using getAttributes function:-

BOOL DirectoryExists(LPCTSTR szPath)
{
  DWORD dwAttrib = GetFileAttributes(szPath);

  return (dwAttrib != INVALID_FILE_ATTRIBUTES && 
         (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}

or you can try this too:-

#include <io.h>     // For access().
#include <sys/types.h>  // For stat().
#include <sys/stat.h>   // For stat().

bool DirectoryExists( const char* path){

    if( _access( path, 0 ) == 0 ){

        struct stat s;
        stat( path, &s);

        return (s.st_mode & S_IFDIR) != 0;
    }
    return false;
}
3
Vivek S On

You can check whether the path is correct or not without using any Windows API as shown below

    /*
     * Assuming that prgchDirPath is path to a directory
     * and not to any file.
     */
    unsigned char IsFilePathCorrect(char* prgchDirPath)
    {
        FILE *fp;
        char path[MAX_PATH] = {0};

        strcpy(path, prgchDirPath);
        strcat(path, "/test.txt");

        fp = fopen(path, "w");
        if (fp == NULL)
            return 0;

        fclose(fp);
        return 1;
    }
0
mvp On

You can simply use access, which is widely supported on Windows, Linux, Mac, etc: access(filepath, 0) returns 0 if file exists, and error code otherwise. On Windows, you will need to #include <io.h>.