Good answers, but I see that most of them have some problems: First of all, I think a good answer should work for full file names that have their own route headers, it should also work for Linux or windows or, like already mentioned should be cross-platform. For most answers; file names without extension, but the path with the name of the folder, including the period, the function will not be able to return the correct extension: examples of some test cases may be as follows:
const char filename1 = {"C:\\init.d\\doc"}; // => No extention const char filename2 = {"..\\doc"}; //relative path name => No extention const char filename3 = {""}; //emputy file name => No extention const char filename4 = {"testing"}; //only single name => No extention const char filename5 = {"tested/k.doc"}; // normal file name => doc const char filename6 = {".."}; // parent folder => No extention const char filename7 = {"/"}; // linux root => No extention const char filename8 = {"/bin/test.d.config/lx.wize.str"}; // ordinary path! => str
The "brian newman" clause will not be executed for filename1 and filename4. and most other reverse search based answers fail for file name1. I suggest including the following method in your source: which is the function returning the index of the first character of the extension or the length of the specified string if not found.
size_t find_ext_idx(const char* fileName) { size_t len = strlen(fileName); size_t idx = len-1; for(size_t i = 0; *(fileName+i); i++) { if (*(fileName+i) == '.') { idx = i; } else if (*(fileName + i) == '/' || *(fileName + i) == '\\') { idx = len - 1; } } return idx+1; }
you can use the above code in your c ++ application as below:
std::string get_file_ext(const char* fileName) { return std::string(fileName).substr(find_ext_idx(fileName)); }
The last time in some cases a folder is given a file name as an argument and includes a period in the folder name, the function returns the layout point of the folder, therefore it is better for the user to first verify that this name is the file name, not the folder name.
AMCoded Nov 08 '14 at 22:49 2014-11-08 22:49
source share