C++ - grep path in linux - c++

I am new to linux and I want to know how to get path which is in the following format - /home/linux/sample/?
I want to write a c++ function which takes the path as input and returns true as if the path has /home/linux/sample/.
Example:
If the path is /home/linux/sample/test.txt should return true
If the path is /home/linux/sample/dir should return true
If the path is /home/linux/user/test.txt should return false
Can some one please help me?
Thanks in advance.

To write such a function you need only std::string:
string str ("There are two needles in this haystack.");
string str2 ("needle");
if (str.find(str2) != string::npos) {
//.. found.
}
If the algorithm will get more sophisticated than I would move to regular expressions.

Looks like you're trying to check if a string is the prefix of another one. In that case, you can rely on std::equal from <algorithm>:
std::string prefix = "/home/linux/sample/";
std::string path0 = "/home/linux/sample/test.txt";
if(std::equal(prefix.begin(), prefix.end(), path0.begin())) {
...
}
The / at the end of prefix is important!

Related

C++ string equivalent for strrchr

Using C strings I would write the following code to get the file name from a file path:
#include <string.h>
const char* filePath = "dir1\\dir2\\filename"; // example
// extract file name (including extension)
const char* fileName = strrchr(progPath, '\\');
if (fileName)
++fileName;
else
fileName = filePath;
How to do the same with C++ strings? (i.e. using std::string from #include <string>)
The closest equivalent is rfind:
#include <string>
std::string filePath = "dir1\\dir2\\filename"; // example
// extract file name (including extension)
std::string::size_type filePos = filePath.rfind('\\');
if (filePos != std::string::npos)
++filePos;
else
filePos = 0;
std::string fileName = filePath.substr(filePos);
Note that rfind returns an index into the string (or npos), not a pointer.
To find the last occurence of a symbol in a string use std::string::rfind
std::string filename = "dir1\\dir2\\filename";
std::size_t pos = filename.rfind( "\\" );
However, if you're handling filenames and pathes more often, have a look at boost::filesystem
boost::filesystem::path p("dir1\\dir2\\filename");
std::string filename = p.filename().generic_string(); //or maybe p.filename().native();
Either call string::rfind(), or call std::find using reverse iterators (which are returned from string::rbegin() and string::rend()).
find might be a little bit more efficient since it explicitly says that you're looking for a matching character. rfind() looks for a substring and you'd give it a length 1 string, so it finds the same thing.
Apart from rfind(), you can also use find_last_of()
You have an example too written in cplusplus.com which is same as your requirement.

Search for presence of a blank space inside a string using find

I have the following code
std::string t = "11:05:47" (No spaces inside)
I want to check if it has an empty space in it (which it doesnt) so I am using
unsigned present = t.find(" ");
if (present!=std::string::npos)
{
//Ends up in here
}
The codes seems to think there is a blank space inside the string any suggestions on what I might be doing wrong
Here are the results
present = 4294967295
t = 11:15:36
IS there a boost library that could help me do this ? Any suggestions ?
Don't use unsigned. std::string::find returns a std::string::size_type, which is usually size_t.
std::string::size_type present = t.find(" ");
if (present!=std::string::npos) {
}
As pointed out by others, you could use C++11's auto to let the compiler deduce what the type of present should be:
auto present = t.find(" ");

C++: how to judge if the path of the file start with a given path

I have a path, for example, named
/my/path/test/mytestpath
, and I want to judge if it start with a given path, for example
/my/path
The C++17 filesystem library is probably the most robust solution. If C++17 is not available to you, Boost.Filesystem provides an implementation for earlier C++ versions. Try something like:
bool isSubDir(path p, path root)
{
while(p != path()) {
if(p == root) {
return true;
}
p = p.parent_path();
}
return false;
}
Substring the length of the string ( /my/path ) of the original (/my/path/test/mytestpath ) from the beginning.
Check whether two strings are equal.
You can do a string compare of the number of characters in the shorter string.
The fact that the characters match of itself won't mean it is a sub-path because you need to check that the next character in the longer string is a '/'
In C you can use strncmp() which takes a length of characters.
In C++ you can use the same or string compare functions. The find() function will work for this but remember to also check that the next character in the main path is a directory separator.
You could "tokenize" your path but that is likely to not be worth it.
std::string::find() returns the index at which a string was found, with an index of 0 being the start of the string:
std::string path("/my/path/test/mytestpath");
// This will check if 'path' begins with "/my/path/".
//
if (0 == path.find("/my/path/"))
{
// 'path' starts with "/my/path".
}

CString extract file path

Hey I'm trying to extract the file path but the problem is that I'm stuck in an infinite loop don't understand why. Please have a look at my code.
CString myString(_T("C:\\Documents and Settings\\admin\\Desktop\\Elite\\Elite\\IvrEngine\\dxxxB1C1.log"));
int pos = myString.Find(_T("\\"));
while (pos != -1)
{
pos = myString.Find(_T("\\"), pos); // it keeps returning 2
}
CString folderPath = myString.Mid(pos);
Now the problem is that, Find() returns 2 the first time I run, but then in the while loop it keeps returning 2, why is the function unable to find the rest '\' ? So now I'm in an infinite loop :(.
It sounds like Find includes the character at the position you give it when searching. So if you give it the position of a character that matches the search, then it will return that same position.
You probably need to change it to:
pos = myString.Find(_T("\\"), pos + 1);
your code will never work! When the while loop finished, the contend of pos can not be used.
Here is a solution which will work:
CString folderPath;
int pos = myString.ReverseFind('\\');
if (pos != -1)
{
folderPath = myString.Left(pos);
}
You can fix the code (see the pos + 1 answers) but I think that you should use _splitpath_s instead which was intended for this kind of operations.
CString::Find always returns the first occurence of the character you're searching for. So it keeps finding the the first "\\" which is at index 2 infinitely since you're searching from 2 which includes that "\\"
I can understand your initial implementation, as the behaviour of CString::Find() seem to have changed over time.
Take a look at the MSDN docs for MFC implementation shipped with VC6 here and at the current implementation here. Especially look at the differences of the description of the 2nd offset parameter.
The solution to your problem is, as already stated above, to add 1 to the search offset of the successive Find() calls. You can also search for single chars (or wchar_ts) like that:
myString.Find(_T('\\'), pos+1);
EDIT:
BTW, take a look at the Path* familly of functions exposed by the shlwapi.dll, declared in shlwapi.h. Especially the PathRemoveFileSpec function might be of interest to you.
in MFC, example to get folder which including executable file:
char ownPth[MAX_PATH];
// Will contain exe path
HMODULE hModule = GetModuleHandle(NULL);
if(NULL == hModule){
return __LINE__;
}
// When passing NULL to GetModuleHandle, it returns handle of exe itself
GetModuleFileName(hModule,ownPth, (sizeof(ownPth)));
modulePath = (LPCSTR)ownPth;
modulePath = modulePath.Left(modulePath.ReverseFind(_T('\\')));
return 0;

Searching CStrings in C++

I was wondering if there is a native C++ (or STL/Boost) function which will search a CString for a specified string?
e.g.
CString strIn = "Test number 1";
CString strQuery = "num";
bool fRet = SomeFn(strIn, StrQuery);
if( fRet == true )
{
// Ok strQuery was found in strIn
...
I have found a small number of functions like CompareNoCase IndexOf etc... but so far they don't really do what I want them to do (or use CLR/.Net)
Thanks!
CString::Find() is what you want, one of the overloads does sub-string searching.
CString strIn = "test number 1";
int index = strIn.Find("num");
if (index != -1)
// ok, found
string::find
Have you tried CString::Find?
It's not STL or boost but since you have two CString's it seems the most reasonable method to use.