C语言的确博大精深,在C语言的世界中遨游了那么多年,发现自己仍是菜鸟一枚,很多利器没有能够驾驭,今天介绍一个神兽,威力无比,但是却很少人能用得好。
函数原型:
#include <string.h> char *strdup(const char *s);
函数介绍:
strdup()函数是c语言中常用的一种字符串拷贝库函数,一般和free()函数成对出现。
strdup()在内部调用了malloc()为变量分配内存,不需要使用返回的字符串时,需要用free()释放相应的内存空间,否则会造成内存泄漏。该函数的返回值是返回一个指针,指向为复制字符串分配的空间;如果分配空间失败,则返回NULL值。
函数实现:
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); }
函数实战:
#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
参考文档:
作者:虚生 出处:https://www.cnblogs.com/dylancao/ 以音频和传感器算法为核心的智能可穿戴产品解决方案提供商 ,提供可穿戴智能软硬件解决方案的设计,开发和咨询服务。 勾搭热线:邮箱:1173496664@qq.com weixin:18019245820 市场技术对接群:347609188 |
![]() |
分类:
C/C++ languare
标签:
C语言
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战