C - 找到完整的命令路径

时间:2015-02-13 16:26:29

标签: c string parsing path

我试图找到某人在终端或控制台窗口中键入的命令的完整路径。我正在尝试使用

 getenv(PATH) 

获得':'命令可能存在的不同路径的分隔字符串,然后使用

stat() 

查看每一个是否存在。

我无法解析getenv()的返回,因为我无法使用字符串库。

getenv(path) returns: 
PATH = /Library/Frameworks/Python.framework/Versions/3.2/bin:/Library/Frameworks/Python.framework/Versions/3.2/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

我在尝试:

char* fullPath = getenv( "PATH" );
struct stat buffer;
int exists; 
char* fileOrDirectory = usersCommand    
exists = stat( file_or_dir, &buffer );  
if ( exists == 0 && ( S_IFDIR & buffer.st_mode ) ) {
    //dir exists
} else if ( exists == 0 && ( S_IFREG & buffer.st_mode ) ) {
    //file exists
} else {
    //neither exists
}

截至目前,我没有使用我的fullPath变量。现在是它只是在我的本地目录中搜索命令?

一个示例命令是' cd'或者' ls'等等。

我如何解析':'分隔字符串,然后在每个字符串上调用stat?除了在文件或目录状态上有一些信息之外我还没有完全理解缓冲的目的,但我觉得它应该采取另一个参数,所以我可以输入我正在搜索的内容以及fullPath。

由于

3 个答案:

答案 0 :(得分:1)

因为不允许使用字符串标准库函数,所以您需要自己编写一个字符串标记生成器,您可以在下面的代码行中执行某些操作,您可能需要对其进行更多优化。

基本上我们在这里做什么

获取路径

找到令牌':'

memcpy substring upto token -1

更新PATH

重复直到'\ 0'。

#define MAX_DIR_PATH_SIZE 500
char *get_directory(char **u_path, int *done)
{
    int i;
    char *temp  = malloc(MAX_DIR_PATH_SIZE);
    //handle error here                                                                                                                                                                                                                           
    memset(temp,0,MAX_DIR_PATH_SIZE);
    if(!u_path || !(*u_path))
        return NULL;
    int index =0 ;

    for(i = 0;i <= MAX_DIR_PATH_SIZE ; i++)
    {
         if(index)
            break;
         switch((*u_path)[i]) // proximity of the brackets and * is important                                                                                                                                                                   
         {
            case '\0':
              *done  = 1;
              index = 1;
              memcpy(temp,*u_path,i+1);
              printf("Last substring %s\n",temp);
            break;
            //Search for token ': ascii = 58'                                                                                                                                                                                                  
            case 0x3A:
              index = 1;
              memcpy(temp,*u_path,i);
              *u_path = *u_path+i+1;
              printf("token found : %s\n",temp);
              break;
           default:
             break;
        }

    }
    //handle error for maximum size overlimit
    return temp;
 }


int main(int argc, char **argv)
{
    char *fullPath = getenv( "PATH" );
    char *u_path = fullPath;
    struct stat buffer;
    int exists;
    int done = 0;
    char* fileOrDirectory = NULL;
    while(!done)
    {
        fileOrDirectory = get_directory(&u_path,&done);
        printf("new path is : %s\n",u_path);
        if(fileOrDirectory)
        {
            exists = stat( fileOrDirectory, &buffer );
            if ( exists == 0 && ( S_IFDIR & buffer.st_mode ) ) {
                printf("directory size %lu\n",buffer.st_size);
            }
            else {
               //do something else                                                                                                                                                                                                                
            }
            free(fileOrDirectory);
        }
    }
    return 0;
}

答案 1 :(得分:0)

这是尝试的事情:

// Variables needed during iteration.
char* start = fullPath;
char sep = ':';
char* iter;
char trialPath[BUFSIZ];

// Get the path
char* originalPath = getenv( "PATH" );

// Make a copy of the path since we are going to modify it
// while we are iterating on it.
char* fullPath = malloc(strlen(originalPath) + 1);
strcpy(fullPath, originalPath);

start = fullPath;

// Iterate over the path.
for ( char* iter = start; *iter != '\0'; ++iter )
{
   if ( *iter == sep )
   {
      *iter = '\0';
      // Now, start is a directory.
      // Check whether the user command is at this location.
      strcpy(trialPath, start);
      strcat(trialPath, "/");
      strcat(trialPath, usersCommand);

      // Now use stat to check whether the file exists and
      // it is an executable.
      // ....


      // If not, reset where start points to.
      start = iter + 1;
   }
}

// Deallocate memory allocated earliner.
free(fullPath);

答案 2 :(得分:0)

函数strtok是标记字符串的标准方法。有了它,您可以构建文件的完整路径名。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

main(int argc, char **argv)
{

    char* fullPath = getenv( "PATH" );
    struct stat buffer;
    int exists;
    char* fileOrDirectory = argv[0];
    char fullfilename[1024];

    char *token = strtok(fullPath, ":");

    /* walk through other tokens */
    while( token != NULL )
    {
        sprintf(fullfilename, "%s/%s", token, fileOrDirectory);
        exists = stat( fullfilename, &buffer );
        if ( exists == 0 && ( S_IFREG & buffer.st_mode ) ) {
            printf("found file %s\n", fullfilename);
        }

        token = strtok(NULL, ":"); /* next token */
    }
    exit(0);
}