-
2007-04-23
C函数提取文件名编号 - [编程]
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://feizf.blogbus.com/logs/5118044.html
现在在做一个软件,遇到这样一个小问题:从目录字符串 "/home/foxman/source_data/234.bin" 中提取出文件数字编号234。C/C++处理字符串的能力并不是很强,所以想到下面的实现代码:
#include "stdio.h"
#include "string.h"
#include "stdlib.h"int main()
{
char *filename="/home/foxman/source_data/234.bin";
char *p=rindex(filename,'/'); //找到最后一个'/'所在位置,此后p="234.bin"
char s[20];
char *q=index(p,'.'); //从p中找到.出现的位置,此后q=".bin"
strncpy(s,p+1,q-p-1); //把p与q之间的字符复制给s,此后s="234"
s[q-p-1]='\0'; //在s数字字符串的末尾加上null
int b;
b=atoi(s); //将字符串s转化为整数, 此后b=234
printf("%d\n",b);
}
几个函数说明:
1. 查找字符串中第一个出现的指定字符
char * index( const char *s, int c);
函数说明 index()用来找出参数s字符串中第一个出现的参数c地址,然后将该字符出现的地址返回。字符串结束字符(NULL)也视为字符串一部分。
2. 查找字符串中最后一个出现的指定字符
char * rindex( const char *s,int c);
函数说明 rindex()用来找出参数s字符串中最后一个出现的参数c地址,然后将该字符出现的地址返回。字符串结束字符(NULL)也视为字符串一部分。
3. 拷贝字符串
char * strncpy(char *dest,const char *src,size_t n);
函数说明 strncpy()会将参数src字符串拷贝前n个字符至参数dest所指的地址。
4. 将字符串转换成整型数
int atoi(const char *nptr); (#include "stdlib.h")
函数说明 atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。
随机文章:
shellcode /bin/sh 2008-11-16ubuntu 8.04建立mysql C开发环境 2008-10-27hacker一段C代码 2008-03-19Linux下读写速度测试 2007-10-09gcc 扩展typeof 2007-09-16
收藏到:Del.icio.us
引用地址:








评论
#include<stdlib.h>
#include<string.h>
int main()
{
char *filename = "/home/ foxman/source_data/1234.bin";
int s = 0;
sscanf(filename,"/home/foxman/source_data/%d.bin",&s);
printf("%d\n",s);
return 0;
}
不过目录是可变的,所以scanf()第一个参数字符串不能固定。
另两种方法提供了一个新的思路。。
#include<string.h>
#include<sys/types.h>
#include<regex.h>
int main()
{
char value[] = "xxx/xxx/xxx/234.bin";
char test[] = "[0-9]{3}";
char buf[4];
reg_t reg;
regmatch_t pm[1];
regcomp(®,test,1);
int rc = regexec(®,value,1,pm,0);
if(rc = REG_NOMATCH)
{
printf("no match\n");
regfree(®);
return -1;
}
int n = pm[0].rm_eo - pm[0].rm_so;
char *base = value+pm[0].rm_so;
strncpy(buf,base,n);
printf("%d\n",atoi(buf));
return 0;
}
// ubuntu 测试通过
2 #include<stdlib.h>
3 #include<sys/types.h>
4 #include<unistd.h>
5 #include<assert.h>
6 int main()
7 {
8 char cmd[] = "echo '/home/foxman/source_data/234.bin' | sed -e 's/\\// /g' |awk '{print substr($4,1,3)}'";
9 FILE *fd=popen(cmd,"r");
10 assert(fd);
11
12 char buf[1024];
14 while(fgets(buf,1024,fd))
15 {
16 printf("GET_FROM_POPEN:\t%d",atoi(buf));
17 }
19 pclose(fd);
20 return 0;
21 }
22
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int main()
{
char *filename="/home/foxman/source_data/234.bin";
char *p;
char *sp;
char *ep;
char s[20];
p = filename;
bzero(s,20);
while(*p)
{
if (*p=='/')
sp = p;
else if(*p=='.')
ep = p;
p++;
}
strncpy(s,sp+1,ep-sp-1);
#if 0
char *p=rindex(filename,'/'); //找到最后一个'/'所在位置,此后p="234.bin"
char s[20];
char *q=index(p,'.'); //从p中找到.出现的位置,此后q=".bin"
strncpy(s,p+1,q-p-1); //把p与q之间的字符复制给s,此后s="234"
s[q-p-1]='\0'; //在s数字字符串的末尾加上null
#endif
int b;
b=atoi(s); //将字符串s转化为整数, 此后b=234
printf("%d\n",b);
return 0;
}