Get filename without extension cpp

Get filename without extension cpp DEFAULT

C++: How to get filename from a path with or without extension | Boost | C++17 FileSytem Library

In this article we will discuss different ways to get filename from a path with or without extension using,

  • Boost Filesystem Library
  • C++17 Filesystem Library
  • Prior to c++11 Days

Suppose we have a file path i.e.

"/home/user/sample/temp/data.csv"
We want to fetch file name from this path i.e. “data.csv”and “data”(With or without extension).

Let’s see how to do that,

Get FileName using Boost & C++17 FileSystem Library

Both Boost & C++17 FileSystem Library provides similar API under different name spaces.

Let’s see how to do that,

Create Path object from given string i.e.

// Create a Path object from File Path filesys::path pathObj(filePath);
Then check if given path has a stem and if yes then get that stem.
// Check if file has stem i.e. filename without extension if(pathObj.has_stem()) { // return the stem (file name without extension) from path object return pathObj.stem().string(); } return "";
stem here represents the filename with extension.

To get the file name without extension all the filename() function on path i.e.

pathObj.filename().string();
Checkout complete function as follows,
/* * Get File Name from a Path with or without extension */ std::string getFileName(std::string filePath, bool withExtension = true) { // Create a Path object from File Path filesys::path pathObj(filePath); // Check if file name is required without extension if(withExtension == false) { // Check if file has stem i.e. filename without extension if(pathObj.has_stem()) { // return the stem (file name without extension) from path object return pathObj.stem().string(); } return ""; } else { // return the file name with extension from path object return pathObj.filename().string(); } }
To use the above function with Boost File System Library, use following header file and namesapce,
#include <boost/filesystem.hpp> namespace filesys = boost::filesystem;
To use the above function with C++17 FileSystem Library, use following header file and namesapce,
#include <experimental/filesystem> namespace filesys = std::experimental::filesystem;
Complete executable example using Boost is as follows,
#include <iostream> #include <cassert> #include <string> #include <boost/filesystem.hpp> namespace filesys = boost::filesystem; /* * Get File Name from a Path with or without extension */ std::string getFileName(std::string filePath, bool withExtension = true) { // Create a Path object from File Path filesys::path pathObj(filePath); // Check if file name is required without extension if(withExtension == false) { // Check if file has stem i.e. filename without extension if(pathObj.has_stem()) { // return the stem (file name without extension) from path object return pathObj.stem().string(); } return ""; } else { // return the file name with extension from path object return pathObj.filename().string(); } } int main() { std::string filePath = "/home/user/sample/temp/data.csv"; // Get File name with extension from file path std::string name = getFileName(filePath); assert(name == "data.csv"); std::cout<<name<<std::endl; // Get File name with extension from file path name = getFileName(filePath, false); assert(name == "data"); std::cout<<name<<std::endl; return 0; }
Output:
data.csv data
To compile the above code in linux using Boost Filesystem Library, use following command,
g++ -std=c++11 example.cpp -lboost_filesystem -lboost_system
To compile the above code in C++17, change the header file and namespace as mentioned above and use following command,
g++ --std=c++17 example.cpp -lstdc++fs

Get File Name using C++ std::string functions

#include <iostream> #include <cassert> #include <string> /* * Get File Name from a Path with or without extension */ std::string getFileName(std::string filePath, bool withExtension = true, char seperator = '/') { // Get last dot position std::size_t dotPos = filePath.rfind('.'); std::size_t sepPos = filePath.rfind(seperator); if(sepPos != std::string::npos) { return filePath.substr(sepPos + 1, filePath.size() - (withExtension || dotPos != std::string::npos ? 1 : dotPos) ); } return ""; } int main() { std::string filePath = "/home/user/sample/temp/data.csv"; // Get File name with extension from file path std::string name = getFileName(filePath); assert(name == "data.csv"); std::cout<<name<<std::endl; // Get File name with extension from file path name = getFileName(filePath, false); std::cout<<name<<std::endl; assert(name == "data.csv"); std::cout<<name<<std::endl; return 0; }
Output:
data.csv data.csv data.csv
 
Sours: https://thispointer.com/c-how-to-get-filename-from-a-path-with-or-without-extension-boost-c17-filesytem-library/

10.13. Extracting a File Extension from a String

Given a filename or a complete path, you need to retrieve the file extension, which is the part of a filename that follows the last period. For example, in the filenames src.cpp, Window.class, and Resume.doc, the file extensions are .cpp, .class, and .doc.

Convert the file and/or pathname to a , use the member function to locate the last period, and return everything after that. Example 10-20 shows how to do this.

Example 10-20. Getting a file extension from a filename

#include <iostream> #include <string> using std::string; string getFileExt(const string& s) { size_t i = s.rfind('.', s.length()); if (i != string::npos) { return(s.substr(i+1, s.length() - i)); } return(""); } int main(int argc, char** argv) { string path = argv[1]; std::cout << "The extension is \"" << getFileExt(path) << "\"\n"; }

To get an extension from a filename, you just need to find out where the last dot “.” is and take everything to the right of that. The standard class, defined in contains functions for doing both of these things: and .

will search backward for whatever you sent it (a in this case) as the first argument, starting at the index specified by the second argument, and return the index where it was found. If the pattern wasn’t found, will return . also takes two arguments. The first is the index of the first element to copy, and the second is the ...

Get C++ Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.

Start your free trial

Sours: https://www.oreilly.com/library/view/c-cookbook/0596007612/ch10s14.html
  1. Praxis 2 physics
  2. Justice illinois crime rate
  3. 3500 lb axle spindles
  4. Robodrill used
  5. Smash bros japanese name

std::filesystem::path::filename

path filename()const;

(since C++17)

Returns the generic-format filename component of the path.

Equivalent to relative_path().empty()? path():*--end().

[edit]Parameters

(none)

[edit]Return value

The filename identified by the path.

[edit]Exceptions

May throw implementation-defined exceptions.

[edit]Example

Run this code

#include <iostream>#include <filesystem>namespace fs = std::filesystem;   int main(){std::cout<< fs::path("/foo/bar.txt").filename()<<'\n'<< fs::path("/foo/.bar").filename()<<'\n'<< fs::path("/foo/bar/").filename()<<'\n'<< fs::path("/foo/.").filename()<<'\n'<< fs::path("/foo/..").filename()<<'\n'<< fs::path(".").filename()<<'\n'<< fs::path("..").filename()<<'\n'<< fs::path("/").filename()<<'\n'<< fs::path("//host").filename()<<'\n';}

Output:

"bar.txt" ".bar" "" "." ".." "." ".." "" "host"

[edit]See also

Sours: https://en.cppreference.com/w/cpp/filesystem/path/filename
if you change a filename extension the file might become unusable

Methods to get filename from a path with or without extension in c++

In this article, we discuss the different methods to get filename from a path with or without extension in c++. The method that we discuss are given below:-

Let’s first understand what we will be going to do in this article. Suppose there is a path name then in this example filename with extension is and filename without extension is . So we will be writing code in c++ to do this task.

Let’s understand all the methods one by one.

Method 1-Using string functions

In this method, we use the string in c++ to do the task. We will use different functions that are used in c++ strings to extract the filename. Let see this with the help of an example.

#include <iostream> #include <string> using std::string; string getFileNameWithExtension(const string& s) { char sep = '/'; #ifdef _WIN32 sep = '\\'; #endif size_t i = s.rfind(sep, s.length()); if (i != string::npos) { string filename = s.substr(i+1, s.length() - i); string rawname = filename.substr(0, s.length()); return(rawname); } return(""); } string getFileNameWithoutExtension(const string& s) { char sep = '/'; #ifdef _WIN32 sep = '\\'; #endif size_t i = s.rfind(sep, s.length()); if (i != string::npos) { string filename = s.substr(i+1, s.length() - i); size_t lastindex = filename.find_last_of("."); string rawname = filename.substr(0, lastindex); return(rawname); } return(""); } int main() { string path = "/home/user/c++/program.c++"; string filename_with_extension = getFileNameWithExtension(path); string filename_without_extension= getFileNameWithoutExtension(path); std::cout << "The file name with extension is \"" << filename_with_extension << "\"\n"; std::cout << "The file name without extension is \"" << filename_without_extension << "\"\n"; }

Output

The file name with extension is "program.c++" The file name without extension is "program"

Method 2-Using C++17 Filesystem library

The Filesystem library provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories. So here we will use the Filesystem library to get filename from a path with and without extension. Let’s write code for this.

#include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::cout << "The file name with extension is " <<fs::path( "/home/user/c++/program.c++" ).filename() << '\n'; std::cout << "The file name without extension is " <<fs::path( "/home/user/c++/program.c++" ).stem() << '\n'; }

Output

The file name with extension is "program.c++" The file name without extension is "program"

So these are the methods to get filename with and without extension in c++.

Related

Categories CPP ProgrammingSours: https://btechgeeks.com/how-to-get-filename-from-a-path-with-or-without-extension-in-cpp/

Extension without cpp filename get

How can I extract the file name and extension from a path in C++

To extract a filename without extension, use boost::filesystem::path::stem instead of ugly std::string::find_last_of(".")


For C++17:

Reference about filesystem: http://en.cppreference.com/w/cpp/filesystem

  • std::filesystem::path::filename
  • std::filesystem::path::stem

As suggested by @RoiDanto, for the output formatting, may surround the output with quotations, e.g.:

You can convert to by if that's what you need, e.g.:


If you want a safe way (i.e. portable between platforms and not putting assumptions on the path), I'd recommend to use .

It would look somehow like this:

Then you can extract various data from this path. Here's the documentation of path object.


BTW: Also remember that in order to use path like

you need to escape the in a string literal:

Or use instead:

This only applies to specifying literal strings in quotes, the problem doesn't exist when you load paths from a file.

Sours: https://newbedev.com/how-can-i-extract-the-file-name-and-extension-from-a-path-in-c
Databases: Extract filename without extension from the absolute location (2 Solutions!!)

How to extract the source filename without path and suffix at compile time?

Using both gcc with -std=c11 and g++ with -std=c++14.

E.g. for a file named it should expand to something like e.g.:

or

as where is a macro (for C sources) or constexpr function (for C++ sources) which results to "Hello".

I have to avoid splitting the string from at runtime, because the path and suffix must not be compiled into the executable in any way.

The solution must be without dependencies to huge libraries such as boost.

As I have no makefiles, solutions like this cannot be used in my case.

Did one have a solution for that?

Edit 2015-07-02:

  • I have no influence on how the compiler and linker was invoked (sometimes via makefile, sometimes from command line, or some IDE (Eclipse CDT managed make, Crossworks, Xcode et cetera. So the solution needs to be in code only.
  • My use case is to provide some kind of "generic region identifier" for a small footprint logging solution. The application code (which uses my logger) should only and within the later calls to e.g. I'll implicitely take use of the automatically generated "generic region identifier".
  • My current solution is that the application code have to declare a (after ) before it could place in its code.

Answer #1:

1. gcc builtin function can get the file name of a full path at compile time.

or

2. c++11 constexpr also can do this at compile time.

c++11 constexpr function can only use a return-statement.

example:

source file name is

use to compile this file.

you can see this.

.LC0 + 19 is the address of file name string without path and suffix

3. c++14 constexpr function can do this in a simple way

c++14 constexpr function can use loop and local variable.

the function will replace with a address of at compiler time. ~

Answered By: pexeer

Answer #2:

extract the base filename at compile time with no preprocessor tricks and no external scripts? c++14? no problem sir.

Answered By: Richard Hodges

Answer #3:

If you run gcc from the folder where the source file is located, you will get a different than if you pass an absolute path (i.e. handed to gcc through an IDE).

  • gives me as .
  • gives me as .

Perhaps calling gcc from the path where the source is located is sufficient as work-around?


EDIT

Here is a "dirty" but safe hack which removes the file extension in compile-time. Not really something I'd recommend, but it was fun to write :) So take it for what it is worth. It only works in C.

The union allocates one member which is large enough to hold the full path minus extension and null terminator. And it allocates one member which is large enough to hold the full path minus extension, though with a null terminator.

The member which is too small to hold the full is initialized with as much of as can fit. This is ok in C but not allowed in C++. If contains , the union member will now be initialized to contain with no null terminator.

There will however still be trailing zeroes after that string, because this hack abuses the fact that the other union member has been initialized according to the rules of "aggregate/union" initialization. This rule forces any remaining items in the "aggregate" to be initialized as if they had static storage duration, i.e to zero. Which happens to be the value of the null terminator.

Answered By: Lundin

Answer #4:

It turns out to be very simple, you just need the preprocessor directive, example

at the top of the file, this as is, if all you want is to hide the file name completely then

would work.

If you don't want to use s, you can use this

The gcc flag above means (from gcc's documentation):

language:

Specify explicitly the language for the following input files (rather than letting the compiler choose a default based on the file name suffix). This option applies to all following input files until the next -x option. Possible values for language are:

If you don't have any sort of script that helps you building the source then there is no way to do it I think.

Also, you can see from the above quote of the gcc documentation, that you can save the files without any extension at all, and then combine @Lundin's original solution with this and use

in this case would expand to , and you would achieve what you want, although you need to compile the file in the same directory where it lives, because otherwise it will contain the path to the file.

Answered By: Iharob Al Asimi

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .


Sours: https://www.py4u.net/discuss/65758

Similar news:

.



966 967 968 969 970