2010-11-30 18 views
29

Estoy implementando la funcionalidad de guardar archivos en una aplicación Qt usando C++.std :: ofstream, compruebe si el archivo existe antes de escribir

Estoy buscando una forma de verificar si el archivo seleccionado ya existe antes de escribirlo, para poder avisar al usuario.

Estoy usando una std::ofstream y no estoy buscando una solución de Boost.

+1

Posibles preguntas duplicadas: http://stackoverflow.com/questions/1383617/how-to-check-if-a-file-exists-and-is-readable-in-c, http://stackoverflow.com/questions/574285/checking-existence-of-a-txt-file-with-c-code, http://stackoverflow.com/questions/268023/whats-the-best-way-to-check-if-a -file-exists-in-c-cross-platform –

+0

agregar un dup: http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c -c11-c – zhangxaochen

Respuesta

60

Ésta es una de mis funciones favoritas tuck-distancia que tener a mano para usos múltiples.

#include <sys/stat.h> 
// Function: fileExists 
/** 
    Check if a file exists 
@param[in] filename - the name of the file to check 

@return true if the file exists, else false 

*/ 
bool fileExists(const std::string& filename) 
{ 
    struct stat buf; 
    if (stat(filename.c_str(), &buf) != -1) 
    { 
     return true; 
    } 
    return false; 
} 

Me parece mucho más buen gusto de tratar de abrir un archivo si no tiene intenciones inmediatas de usarlo para E/S.

+2

+1 para un ejemplo que usa stat en lugar de abrir un archivo solo para cerrarlo. –

+5

¿No es una estadística no estándar? – HighCommander4

+12

+1 pero 'return stat (filename.c_str(), & buf)! = 1;' es bastante más compacto. –

7
fstream file; 
file.open("my_file.txt", ios_base::out | ios_base::in); // will not create file 
if (file.is_open()) 
{ 
    cout << "Warning, file already exists, proceed?"; 
    if (no) 
    { 
     file.close(); 
     // throw something 
    } 
} 
else 
{ 
    file.clear(); 
    file.open("my_file.txt", ios_base::out); // will create if necessary 
} 

// do stuff with file 

Tenga en cuenta que en el caso de un archivo existente, esto lo abrirá en modo de acceso aleatorio. Si lo prefiere, puede cerrarlo y volver a abrirlo en modo de adición o truncado.

37
bool fileExists(const char *fileName) 
{ 
    ifstream infile(fileName); 
    return infile.good(); 
} 

Este método es hasta ahora el más corto y portátil. Si el uso no es muy sofisticado, este es uno que yo buscaría. Si también desea solicitar una advertencia, lo haría en general.

+7

Explicación: Utiliza el constructor ifstream para intentar abrir el archivo para su lectura. Cuando la función retorna y el ifstream sale del alcance, su destructor cerrará implícitamente el archivo (en caso de que el archivo existiera y el abierto tuviera éxito). – grubs

2

Una de las maneras sería hacer stat() y verificar en errno.
Un código de ejemplo se vería mirar esto:

#include <sys/stat.h> 
using namespace std; 
// some lines of code... 

int fileExist(const string &filePath) { 
    struct stat statBuff; 
    if (stat(filePath.c_str(), &statBuff) < 0) { 
     if (errno == ENOENT) return -ENOENT; 
    } 
    else 
     // do stuff with file 
} 

Esto funciona independientemente de la corriente. Si aún prefiere verificar usando ofstream, simplemente marque usando is_open().
Ejemplo:

ofstream fp.open("<path-to-file>", ofstream::out); 
if (!fp.is_open()) 
    return false; 
else 
    // do stuff with file 

Espero que esto ayude. Gracias!

Cuestiones relacionadas