2010-09-30 17 views

Respuesta

20

Puede llamar al FindFirstFile.

Este es un ejemplo que acabo de Knocked Up:

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

int fileExists(TCHAR * file) 
{ 
    WIN32_FIND_DATA FindFileData; 
    HANDLE handle = FindFirstFile(file, &FindFileData) ; 
    int found = handle != INVALID_HANDLE_VALUE; 
    if(found) 
    { 
     //FindClose(&handle); this will crash 
     FindClose(handle); 
    } 
    return found; 
} 

void _tmain(int argc, TCHAR *argv[]) 
{ 
    if(argc != 2) 
    { 
     _tprintf(TEXT("Usage: %s [target_file]\n"), argv[0]); 
     return; 
    } 

    _tprintf (TEXT("Looking for file is %s\n"), argv[1]); 

    if (fileExists(argv[1])) 
    { 
     _tprintf (TEXT("File %s exists\n"), argv[1]); 
    } 
    else 
    { 
     _tprintf (TEXT("File %s doesn't exist\n"), argv[1]); 
    } 
} 
+0

Olvidó llamar a 'FindClose'. Y no puede devolver un valor de una función vacía. –

+0

@DavidHeffernan - corregido - gracias. –

+3

Mitad corregida. Debe verificar FILE_ATTRIBUTE_DIRECTORY. –

28

Puede hacer uso de la función GetFileAttributes. Devuelve 0xFFFFFFFF si el archivo no existe.

+11

interesante historia sobre GetFileAttributes y por qué es el método preferido en el código de Windows por Raymond Chen: http://blogs.msdn.com/b/oldnewthing/archive/2007/10/23/5612082.aspx –

+1

Debe verificar que el objeto sea un directorio. –

+6

En realidad, devuelve 'INVALID_FILE_ATTRIBUTES' si el archivo no existe. En 64 bits podría ser '0xFFFFFFFFFFFFFFFF'. –

158

Uso GetFileAttributes para comprobar que existe el objeto del sistema de archivos y que no es un directorio.

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

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

Copiado del How do you check if a directory exists on Windows in C?

+3

+1 debido a un ejemplo de código corto. Los ejemplos de código son un ahorro de tiempo para comenzar. – nalply

+0

Me gustaría señalar que su función devuelve bool y no BOOL. –

+0

Para C++ sí, para C, es un BOOL –

1

Usted puede tratar de abrir el archivo. Si falló, significa que no existe en la mayoría del tiempo.

+0

Iría con CreateFile -> CloseHandle. más fácil y más barato. – OSH

+1

Un archivo abierto también puede fallar si los archivos existen pero el usuario no tiene suficientes privilegios para abrir el archivo. En estos días, esa es una ** muy ** situación común. – JackLThornton

6

Otra opción: 'PathFileExists'.

Pero probablemente vaya con GetFileAttributes.

+1

Además 'PathFileExists' requiere el uso de" Shlwapi.dll "(que no está disponible en algunas versiones de Windows) y es un poco más lento que' GetFileAttributes'. – Bitterblue

+1

+1 para esta buena alternativa –

+0

Pero no le dice si existió un archivo o directorio. –

0

Otra más genérico manera no ventanas:

static bool FileExists(const char *path) 
{ 
    FILE *fp; 
    fpos_t fsize = 0; 

    if (!fopen_s(&fp, path, "r")) 
    { 
     fseek(fp, 0, SEEK_END); 
     fgetpos(fp, &fsize); 
     fclose(fp); 
    } 

    return fsize > 0; 
} 
+0

si va a use fopen et al. También puede usar '_access (0)'. –

12

¿Qué hay de simplemente:

#include <io.h> 
if(_access(path, 0) == 0) 
    ... // file exists 
Cuestiones relacionadas