108 votes

Obtenir un nom de fichier à partir d'un chemin

Quelle est la façon la plus simple d'obtenir le nom du fichier à partir d'un chemin ?

string filename = "C:\\MyDirectory\\MyFile.bat"

Dans cet exemple, je devrais obtenir "MonFichier". sans extension.

2 votes

Rechercher à partir de l'arrière jusqu'à ce que vous frappiez un retour arrière ?

2 votes

@KerrekSB, vous voulez dire barre oblique inversée ;)

0 votes

J'ai un std::string qui contient le chemin d'un fichier "c : \\MyDirectory\\Myfile.pdf "Je dois renommer ce fichier en monfichier_md.pdf et je dois donc obtenir le nom du fichier à partir du chemin.

2voto

Lucian Points 1071
m_szFilePath.MakeLower();
CFileFind finder;
DWORD buffSize = MAX_PATH;
char longPath[MAX_PATH];
DWORD result = GetLongPathName(m_szFilePath, longPath, MAX_PATH );

if( result == 0)
{
    m_bExists = FALSE;
    return;
}
m_szFilePath = CString(longPath);
m_szFilePath.Replace("/","\\");
m_szFilePath.Trim();
//check if it does not ends in \ => remove it
int length = m_szFilePath.GetLength();
if( length > 0 && m_szFilePath[length - 1] == '\\' )
{
    m_szFilePath.Truncate( length - 1 );
}
BOOL bWorking = finder.FindFile(this->m_szFilePath);
if(bWorking){
    bWorking = finder.FindNextFile();
    finder.GetCreationTime(this->m_CreationTime);
    m_szFilePath = finder.GetFilePath();
    m_szFileName = finder.GetFileName();

    this->m_szFileExtension = this->GetExtension( m_szFileName );

    m_szFileTitle = finder.GetFileTitle();
    m_szFileURL = finder.GetFileURL();
    finder.GetLastAccessTime(this->m_LastAccesTime);
    finder.GetLastWriteTime(this->m_LastWriteTime);
    m_ulFileSize = static_cast<unsigned long>(finder.GetLength());
    m_szRootDirectory = finder.GetRoot();
    m_bIsArchive = finder.IsArchived();
    m_bIsCompressed = finder.IsCompressed();
    m_bIsDirectory = finder.IsDirectory();
    m_bIsHidden = finder.IsHidden();
    m_bIsNormal = finder.IsNormal();
    m_bIsReadOnly = finder.IsReadOnly();
    m_bIsSystem = finder.IsSystem();
    m_bIsTemporary = finder.IsTemporary();
    m_bExists = TRUE;
    finder.Close();
}else{
    m_bExists = FALSE;
}

La variable m_szFileName contient le nom du fichier.

2voto

typedef Points 372

Cela devrait aussi fonctionner :

// strPath = "C:\\Dir\\File.bat" for example
std::string getFileName(const std::string& strPath)
{
    size_t iLastSeparator = 0;
    return strPath.substr((iLastSeparator = strPath.find_last_of("\\")) != std::string::npos ? iLastSeparator + 1 : 0, strPath.size() - strPath.find_last_of("."));
}

Si vous pouvez l'utiliser, Qt fournit QString (avec split, trim etc), QFile, QPath, QFileInfo etc pour manipuler les fichiers, les noms de fichiers et les répertoires. Et bien sûr, c'est aussi une forme de plafting croisé.

2voto

hkBattousai Points 1930

Ne pas utiliser _splitpath() y _wsplitpath() . Ils ne sont pas sûrs, et ils sont obsolètes !

Utilisez plutôt leurs versions sûres, à savoir _splitpath_s() y _wsplitpath_s()

1voto

Romi Halasz Points 1089

Par ailleurs, il peut être intéressant de se pencher sur les expressions régulières. Vous pouvez trouver beaucoup d'informations ici : http://www.regular-expressions.info/tutorial.html

1voto

Alex Points 728

Une fonction très simple et courte qui retourne le nom du fichier + le chemin que j'ai créé et qui n'utilise aucune dépendance :

const char* GetFileNameFromPath(const char* _buffer)
{
    char c;
    int  i;
    for (i = 0; ;++i) {
        c = *((char*)_buffer+i);
        if (c == '\\' || c == '/')
            return GetFileNameFromPath((char*)_buffer + i + 1);
        if (c == '\0')
            return _buffer;
    }
    return "";
}

Pour obtenir uniquement le nom du fichier sans l'extension vous pourriez changer c == '\0' à c == '.' .

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X