How to remove file extension in C++

2 Answers

0 votes
#include <iostream>
#include <string>

/*
 * Removes the last file extension from a filename or path.
 *
 * Examples:
 *   "document.pdf"      -> "document"
 *   "archive.tar.gz"    -> "archive.tar"
 *   "photo.jpg"         -> "photo"
 *   "README"            -> "README"
 *   "/tmp/file.txt"     -> "/tmp/file"
 *   "C:\\temp\\a.txt"   -> "C:\\temp\\a"
 *
 * Parameters:
 *   path - Input filename or path.
 *
 * Returns:
 *   A new string without the last file extension.
 *
 * Time Complexity: O(n)
 * Space Complexity: O(n)
 */
std::string removeFileExtension(const std::string& path)
{
    // Find the last path separator.
    const std::size_t lastSlash =
        path.find_last_of("/\\");

    // Find the last dot.
    const std::size_t lastDot =
        path.find_last_of('.');

    // No extension found.
    if (lastDot == std::string::npos) {
        return path;
    }

    // Dot belongs to a directory name, not the filename.
    if (lastSlash != std::string::npos && lastDot < lastSlash) {
        return path;
    }

    // Return everything before the extension.
    return path.substr(0, lastDot);
}

int main()
{
    std::cout << removeFileExtension("document.pdf") << '\n';
    std::cout << removeFileExtension("archive.tar.gz") << '\n';
    std::cout << removeFileExtension("/tmp/file.txt") << '\n';
    std::cout << removeFileExtension("README") << '\n';

    return 0;
}


/*
run:

document
archive.tar
/tmp/file
README

*/

 



answered Oct 12 by avibootz
0 votes
#include <filesystem>
#include <iostream>
#include <string>

/*
 * Removes the last file extension using std::filesystem.
 */
std::string removeFileExtension(const std::string& path)
{
    std::filesystem::path p(path);
    p.replace_extension();
    
    return p.string();
}

int main()
{
    std::cout << removeFileExtension("document.pdf") << '\n';
    std::cout << removeFileExtension("archive.tar.gz") << '\n';
}


/*
run:

document
archive.tar

*/

 



answered Oct 12 by avibootz
...