我正在创建一个函数,它将完整的 unix 文件名(如 /home/earlz/test.bin)拆分为各个部分。我有一个功能,它适用于前两部分完美,但之后它会产生错误的输出......
strlcpy_char 将使用 term 作为终止符以及 0 来复制字符串。如果以 term 终止,则 term 将是字符串的最后一个字符,然后为 null。
返回 trg 字符串长度...
int strlcpy_char(char *trg,const char *src,int max,char term){
int i;
if(max==0){return 0;}
for(i=0;i<max-1;i++){
if(*src==0){
*trg=0;
return i;
}
if(*src==term){
*trg=term;
trg++;
*trg=0; //null terminate
return i+1;
}
*trg=*src;
src++;
trg++;
}
*trg=0;
return max;
}
.
int get_path_part(char *file,int n,char *buf){
int i;
int current_i=0;
//file is assumed to start with '/'so it skips the first character.
for(i=0;i<=n;i++){
current_i++;
current_i=strlcpy_char(buf,&file[current_i],MAX_PATH_PART_SIZE,'/');
if(current_i<=1){ //zero length string..
kputs("!"); //just a debug message. This never happens with the example
return -1; //not enough parts to the path
}
}
if(buf[current_i-1]=='/'){
return 1; //is not the last part
}else{
return 0; //is the last part(the file part)
}
}
我用这段代码来测试它:
kputs("test path: ");
kgets(cmd);
kputs("\n");
char *tmp=malloc(256);
int i=0;
get_path_part(cmd,i,tmp);
kputs(tmp);
kputs("\n");
i=1;
get_path_part(cmd,i,tmp);
kputs(tmp);
kputs("\n");
i=2;
get_path_part(cmd,i,tmp);
kputs(tmp);
kputs("\n");
当我尝试像“/home/test.bin”这样的东西时,它可以正常输出
/家 /test.bin
但是当我尝试“/home/earlz/test.bin”时,我得到了
/家 /厄尔兹 /arlz
正如我一直在寻找的那样,任何人都在我的代码中看到了问题,但我看不到任何问题。
另外,在您说“但是有一个库”之前,我是在操作系统内核中执行此操作的,因此我几乎没有标准库。我只有 string.h 的一部分,这就是标准的内容。