I am creating a function that will split the full name of the unix file (e.g. / home / earlz / test.bin) into separate parts. I have a function, and it works fine for the first two parts, but after that it creates an erroneous result ...
strlcpy_char will copy the string using the term as a terminator, as well as 0. If it ends with a term, then the term will be the last character of the string, then null.
returns the string length 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;
.
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) } }
I use this code to verify it:
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");
When I try something like "/home/test.bin", it works correctly, outputting
/ home
/test.bin
But when I try "/home/earlz/test.bin", I get
/ home
/ earlz
/ arlz
Does anyone see a problem in my code as I searched, but I just don't see any problem.
Also, before you say “but there is a library for this,” I do it in the kernel of the operating system, so I hardly have a standard library. I have only parts of string.h and really, what about this for the standard.