C语言的确博大精深,在C语言的世界中遨游了那么多年,发现本身还是菜鸟一枚,不少利器没有可以驾驭,今天介绍一个神兽,威力无比,可是却不多人能用得好。函数
函数原型:spa
#include <string.h> char *strdup(const char *s);
函数介绍:.net
strdup()函数是c语言中经常使用的一种字符串拷贝库函数,通常和free()函数成对出现。指针
函数实现:code
char * __strdup(const char *s) { size_t len = strlen(s) +1; void *new = malloc(len); if (new == NULL) return NULL; return (char *)memecpy(new,s,len); }
函数实战:blog
#include <syslib.h> #include<string.h> int main(void) { char *src =”This is the strdup test”; char *dest; dest = strdup(s); printf(“the dest %s\n”,dest); return 0; }
运行结果是:内存
the dest This is the strdup test
经常使用方法:文档
#include <stdio.h> #include <string.h> #include <stdio.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #include <string.h> #include <getopt.h> static struct option main_options[] = { { "help", 0, 0, 'h' }, { "verbose", 0, 0, 'v' }, { "msbc", 0, 0, 'm' }, { "subbands", 1, 0, 's' }, { "bitpool", 1, 0, 'b' }, { "joint", 0, 0, 'j' }, { "dualchannel",0, 0, 'd' }, { "snr", 0, 0, 'S' }, { "blocks", 1, 0, 'B' }, { 0, 0, 0, 0 } }; int main(int argc, char *argv[]) { char *output = NULL; int i, opt, tofile = 0; bool msbc = false; while ((opt = getopt_long(argc, argv, "+hmvd:f:", main_options, NULL)) != -1) { switch(opt) { case 'h': exit(0); case 'v': break; case 'm': msbc = true; break; case 'd': free(output); output = strdup(optarg); tofile = 0; break; case 'f' : free(output); output = strdup(optarg); //printf("%s",output); tofile = 1; break; default: exit(1); } } argc -= optind; argv += optind; optind = 0; if (argc < 1) { exit(1); } for (i = 0; i < argc; i++) printf("%s \n\t",argv[i]); free(output); return 0; }
运行结果:字符串
## ./strfile -f test.wav new.wav testb.wav
new.wav
testb.wav
get
参考文档: