C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在C中生成路径的最佳方法是什么?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在运行时生成三种不同类型的路径:

> / sys / class / gpio / gpio%d
> / sys / class / gpio / gpio%d / value
> / sys / class / gpio / gpio%d / direction

目前我通过执行以下操作生成这些:

#define GPIO_PATH_BASE "/sys/class/gpio/gpio"
#define GPIO_PATH_DIRECTION "/direction"
#define GPIO_PATH_VALUE "/value"

int open_gpio(const char * port) {
    char * base_path = (char *) malloc(sizeof(GPIO_PATH_BASE) + sizeof(port));
    strcpy(base_path,GPIO_PATH_BASE);
    strcat(base_path,port);

    char * value_path = (char *) malloc(sizeof(base_path) + sizeof(GPIO_PATH_value));
    strcpy(value_path,(const char *) base_path);
    strcat(value_path,GPIO_PATH_value);

    char * dir_path = (char *) malloc(sizeof(base_path) + sizeof(GPIO_PATH_DIRECTION));
    strcpy(dir_path,(const char *) base_path);
    strcat(dir_path,GPIO_PATH_DIRECTION);
}

我实际上对这种方法很不满意.是否有可能让宏给我这个东西或者我应该创建一个辅助函数

博多

解决方法

如果您的系统支持它,那么asprintf()是最简单的机制:

#define GPIO_PATH_BASE      "/sys/class/gpio/gpio"
#define GPIO_PATH_DIRECTION "/direction"
#define GPIO_PATH_VALUE     "/value"

int open_gpio(const char * port)
{
    char *base_path  = asprintf("%s%s",GPIO_PATH_BASE,port);
    char *value_path = asprintf("%s%s",base_path,GPIO_PATH_value);
    char *dir_path   = asprintf("%s%s",GPIO_PATH_DIRECTION);
    //...do some work with these...or return them...
    //...should check for Failed alLOCATIOns,too...
}

如果你的系统不支持asprintf(),你可以用以下方法“伪造”它:

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

/* Should be in a header */
#ifndef HAVE_ASPRINTF
extern int asprintf(char **ret,const char *format,...);
extern int vasprintf(char **ret,va_list args);
#endif

#ifndef HAVE_ASPRINTF

int vasprintf(char **ret,va_list args)
{
    va_list copy;
    va_copy(copy,args);

    /* Make sure return pointer is determinate */
    *ret = 0;

    int count = vsnprintf(NULL,format,args);
    if (count >= 0)
    {
        char* buffer = malloc(count + 1);
        if (buffer != NULL)
        {
            count = vsnprintf(buffer,count + 1,copy);
            if (count < 0)
            {
                free(buffer);
                buffer = 0;
            }
            *ret = buffer;
        }
    }

    va_end(copy);

    return count;
}

int asprintf(char **ret,...)
{
    va_list args;
    va_start(args,format);
    int count = vasprintf(ret,args);
    va_end(args);
    return(count);
}

#endif /* HAVE_ASPRINTF */

大佬总结

以上是大佬教程为你收集整理的在C中生成路径的最佳方法是什么?全部内容,希望文章能够帮你解决在C中生成路径的最佳方法是什么?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。