c - 获取 argv[0] 中 n 和 argv 长度之间的子字符串

标签 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 可执行文件,您可以通过调用带有其名称的符号链接(symbolic link)来运行小程序。

例如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;
}

最佳答案

这是一个带有注释的程序,解释了如何做你想做的事情。希望它能帮助您学习如何解决此类问题。

#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;
}

关于c - 获取 argv[0] 中 n 和 argv 长度之间的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26242018/

相关文章:

c - 使用 libxml2 删除 xml 中的空白

c - 如何调用名称与c中的局部变量名称相同的函数

c - 结束对 AT 命令的响应

c - 我已经使用堆栈和相邻列表为图编写了 DFS,但它没有像应该的那样工作

javax.validation : Constraint to validate a string length in bytes

c++ - 将数学符号存储到字符串C++中

ruby - Ruby 中的 str.each 不工作

python - 具有特定格式的子字符串提取

c - 使用 'srtchr()' 搜索子串

MySql-拆分单元格并插入到另一个表中