在n和argv的长度之间获取argv [0]的子串

时间:2014-10-07 17:47:09

标签: c string substring

我正在尝试获取argv[0]的子字符串并将其输出到另一个字符串。我已经得到了我想要的职位,我只是无法弄清楚如何从其他答案中做到这一点。这是我到目前为止所得到的:

#include "echo.h"
#include "whoami.h"
#include <string.h>

int main(int argc, char *argv[])
{
    // applet_length: Length of first arg filename excluding things like "./"
    int applet_length = sizeof(argv[0]);
    // real_length: Full length of first argument
    int real_length = 0;
    while ((argv[0])[real_length])
        real_length++;
    int start = real_length - applet_length;
}

start是我要从中开始子串的点,而real_lengthargv[0]的总长度。我该怎么做呢?

我这样做的目的是为了制作像BusyBox这样的coreutils可执行文件,你可以通过调用带有名字的符号链接来运行applet。

E.g。 argv[0]"test1234",起点为4,real_length为8,输出为"1234"


我最终得到了:

#include "echo.h"
#include "whoami.h"
// etc.
#include <string.h>
#include <libgen.h>

int main(int argc, char *argv[])
{
    char *applet = basename(argv[0]);
    if (!strcmp(applet, "echo"))
        echo(argc, argv);
    else if (!strcmp(applet, "whoami"))
        whoami(argc, argv);
    // etc.
    return 0;
}

1 个答案:

答案 0 :(得分:0)

这是一个包含评论的程序,解释了如何做你想做的事。希望它能帮助您学习如何解决这些问题。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Use if strdup() is unavailable.  Caller must free the memory returned. */
char *dup_str(const char *s)
{
    size_t n = strlen(s) + 1;
    char *r;
    if ((r = malloc(n)) == NULL) {
        return NULL;
    }
    strcpy(r, s);
    return r;
}

/* Use if POSIX basename() is unavailable */
char *base_name(char *s)
{
    char *start;

    /* Find the last '/', and move past it if there is one.  Otherwise return
       a copy of the whole string. */
    /* strrchr() finds the last place where the given character is in a given
       string.  Returns NULL if not found. */
    if ((start = strrchr(s, '/')) == NULL) {
        start = s;
    } else {
        ++start;
    }
    /* If you don't want to do anything interesting with the returned value,
       i.e., if you just want to print it for example, you can just return
       'start' here (and then you don't need dup_str(), or to free
       the result). */
    return dup_str(start);
}

/* test */
int main(int argc, char *argv[])
{
    char *b = base_name(argv[0]);

    if (b) {
        printf("%s\n", b);
    }
    /* Don't free if you removed dup_str() call above */
    free(b);

    return EXIT_SUCCESS;
}