Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Credits: w2ch Anon */
- /* File:CheckIfFileExist.cpp */
- #include <windows.h>
- #include <stdio.h>
- bool DoesFileExist(const char *szpFilePath, const char *szFileName)
- {
- WIN32_FIND_DATA ffd;
- char szDir[MAX_PATH];
- HANDLE hFind = INVALID_HANDLE_VALUE;
- DWORD dwRet;
- /* If no file to search for: Return false. */
- if (szFileName == NULL) return false;
- /* Check that the input path plus 3 is not longer than MAX_PATH.
- * Three characters are for the "\*" plus NULL appended below.
- * At the same time prepare string for use with FindFile functions. */
- if (szpFilePath == NULL)
- {
- /* If no szpFilePath, use the directory the file is in */
- dwRet = GetCurrentDirectory((sizeof(szDir) / sizeof(*szDir)) - 3, szDir);
- /* ERROR: GetCurrentDirectory failed, GetLastError() */
- if (dwRet == 0) return 0;
- /* ERROR: Buffer(string) too small; need %d characters\n, */
- if (dwRet > MAX_PATH - 3) return 0;
- }
- else
- {
- for (dwRet = 0; szpFilePath[dwRet] != '\0'; ++dwRet);
- /* ERROR: Buffer(string) too small; need %d characters\n, */
- if (dwRet > MAX_PATH - 3) return 0;
- for (int n = dwRet; n; szDir[n] = szpFilePath[n], --n);
- szDir[0] = szpFilePath[0];
- }
- /* Add "\*" to the directory name. */
- szDir[dwRet] = '\\';
- szDir[++dwRet] = '*';
- szDir[++dwRet] = '\0';
- /* Find the first file in the directory. */
- hFind = FindFirstFileA(szDir, &ffd);
- if (INVALID_HANDLE_VALUE == hFind) return 0; /* ERROR "FindFirstFile" */
- /* List all the files in the directory with some info about them. */
- do
- {
- /* Only compare to files and not other objects, e.g: directorys */
- if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
- {
- /* Compare if ffd.cFileName match szFileName and if yes return true */
- for (dwRet = 0; ffd.cFileName[dwRet] == szFileName[dwRet] && szFileName[dwRet]; ++dwRet);
- if (!ffd.cFileName[dwRet])
- {
- FindClose(hFind);
- return true;
- }
- }
- } while (FindNextFile(hFind, &ffd) != 0);
- dwRet = GetLastError();
- if (dwRet != ERROR_NO_MORE_FILES); // ERRPR: "FindFirstFile"
- /* If we return here we did not find the file we were looking for */
- FindClose(hFind);
- return false;
- }
- /* find if in the current directory there is a file named argv[0] */
- int main(int argc, char *argv[])
- {
- bool bFileExist;
- if (argc == 2) bFileExist = DoesFileExist(NULL, argv[1]);
- else if (argc == 3) bFileExist = DoesFileExist(argv[1], argv[2]);
- else
- {
- fprintf(stdout, "Usages:%s [filepath] [file]", argv[0]);
- return 0;
- }
- if (bFileExist)
- {
- fprintf(stdout, "The file exist!");
- }
- else
- {
- fprintf(stdout, "The file dose not exist!");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment