在C中生成路径的最佳方法是什么?
发布时间:2020-12-16 10:24:31 所属栏目:百科 来源:网络整理
导读:我需要在运行时生成三种不同类型的路径: / 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 G
我需要在运行时生成三种不同类型的路径:
> / sys / class / gpio / gpio%d 目前我通过执行以下操作生成这些: #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 */ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |