> / 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_ASPRINTFextern int asprintf(char **ret,const char *format,...);extern int vasprintf(char **ret,va_List args);#endif#ifndef HAVE_ASPRINTFint 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中生成路径的最佳方法是什么?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)