Solved

How to  Cross-verify path ....using  C ++ function

Posted on 2004-04-07
10
250 Views
Last Modified: 2012-05-04
Hi

I have this question w r t C++......

I have set a particular directory for my executables........
say C:\Ruff\exec

My requirement is that when a user ie UNIX based is in a particular path and wants to execute one of my exe's ...... i need the system to corss-verify whether the user is in the same path as that defined by me...............

How do i do this in C++. are there any C++ functions for doing this ....P S : its a unix based environment where im deploying the C++ Code....



Thank You

In Advance

RonCOde
0
Comment
Question by:RonCode
  • 3
  • 2
  • 2
10 Comments
 
LVL 12

Expert Comment

by:stefan73
ID: 10773242
Hi RonCode,
You can use the getcwd() function:

#include <unistd.h>
#include <stdio.h>

main(){
    char dirbuf[1024];

    if(getcwd(dirbuf,sizeof(dirbuf))){
        printf("Your current directory is: %s\n",dirbuf);

}

The prototype is:
extern char *getcwd(char *buf, size_t size);


Cheers,
Stefan
0
 

Author Comment

by:RonCode
ID: 10775381
Hi

I would like to cross verify the current working directory with the path i have set

How do i????
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10775496
RonCode,
Just to understand you fully - you want to check if the current directory is part of $PATH?
Or do you want to add the current directory to $PATH?

Or is it that you want to check that the user called exactly the binary stored in a particular path?

Stefan
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 10776063
GetModulFileName() gives the path of the executable.

GetCurrentDirectory() gives the current working directory.

You may compare both paths and the directory should be identical to the directory part of the executable path.

    char szExePath[512];
    int lenExe = GetModuleFileName( NULL,  szExePath,   sizeof(szExePath));
    char szWorkingDir[512];
    int lenDir = GetCurrentDirectory(sizeof(szWorkingDir), szWorkingDir);
    if (lenDir < lenExe && strstr(szExePath, szWorkingDir) == szExePath)
    {
         // ok, check it isn't a sub directory
         int pos = strrchr(szExePath, '\\');
         if (pos == lenDir)
         {
             // all ok now, the executable has been started from the current working directory    
         }
    }
 
Regards, Alex
0
 

Author Comment

by:RonCode
ID: 10781058
Yeah check if the current directory is part of $PATH?

RonCode
0
 
LVL 12

Accepted Solution

by:
stefan73 earned 63 total points
ID: 10782551
RonCode,
> Yeah check if the current directory is part of $PATH?

That is tricky. You could have tons of possibilities:

1. Full path.
2. "."
3. :: (empty means current dir)
4. Via soft link
5. Any combinations of 1,2,4 and additional ../current_dir

Probably the easiest way is to check if your binary was found in the current directory with the "which" command.

Stefan
0
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 62 total points
ID: 10785662
Try this:

#include <windows.h>

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main(int nArg, char* pszArgs[])
{
    // Get write access to the directory 'file'

    char szWorkingDir[1024];
    int lenDir = GetCurrentDirectory(sizeof(szWorkingDir), szWorkingDir);
    szWorkingDir[lenDir] = '\0';

    char szPath[1024];
    int lenPath = GetEnvironmentVariable("PATH", szPath, sizeof(szPath));

    HANDLE hdlDir = CreateFile (szWorkingDir,
                                GENERIC_READ,
                                FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
                                NULL,
                                OPEN_EXISTING,
                                FILE_FLAG_BACKUP_SEMANTICS,
                                NULL
                             );

    if (hdlDir == INVALID_HANDLE_VALUE)
    {
       cout << "Current directory " << szWorkingDir << " couldn't be opened. Error = " << GetLastError() << endl;
       return 2;
    }

    BY_HANDLE_FILE_INFORMATION fileInfo;
    if (!GetFileInformationByHandle(hdlDir, &fileInfo))
    {
       cout << "Current directory " << szWorkingDir << " couldn't get file info. Error = " << GetLastError() << endl;
       return 3;
    }
    CloseHandle(hdlDir);


    string        strDir(szWorkingDir);
    int           pos = strDir.find_last_of("\\/");
    if (pos != string::npos)
        strDir.erase(0, pos+1);
    string        strPath(szPath);
    stringstream  ssPath(strPath);

    while (!ssPath.eof())
    {
        getline(ssPath, strPath, ';');
        if (strPath.empty())
            continue;
        HANDLE hdl = CreateFile(strPath.c_str(), GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ, NULL,
                                    OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

        if (hdl == INVALID_HANDLE_VALUE)
            continue;

        BY_HANDLE_FILE_INFORMATION info;
        if (!GetFileInformationByHandle(hdl, &info))
        {
           cout << "Current directory " << strPath << " couldn't get file info. Error = " << GetLastError() << endl;
           CloseHandle(hdl);
           continue;  // ignore error
        }
       
        if (fileInfo.dwVolumeSerialNumber == info.dwVolumeSerialNumber &&
            fileInfo.nFileIndexLow  == info.nFileIndexLow &&
            fileInfo.nFileIndexHigh == info.nFileIndexHigh)
        {
            cout << "Current directory " << szWorkingDir << " is part of %PATH% as " << strPath << endl << endl;
            CloseHandle(hdl);
            return 0;
        }
        CloseHandle(hdl);

    }

    cout << "current directory " << szWorkingDir << " is not part of %PATH%: " << endl << szPath << endl << endl;
    return 1;

}


There might be an easier way using SearchPath function of Windows API. However, i did find it after i had written that working code.

Regards, Alex
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question