linux - C — using chdir() function -
i'm trying use chdir()
function can't work out.
i'm reading user , find out if using "cd". error. doing wrong?
code:
int * status=0; char * buf = 0; char arguments[2048]; buf = getcwd(buf,path_max); printf("%s >",buf); fgets(arguments,2048,stdin); if( strncmp(arguments,"quit",4)==0 ){ printf("exit...\n"); break; } else if(strncmp(arguments,"cd",2)==0 ){ int ret; printf("\ngot = %s\n",(arguments+2)); ret = chdir ((arguments+2)); if(ret!=0){ perror("error:"); } }
if line being entered like:
cd xyzzy
then directory starts @ offset 3, not 2. in addition, fgets
gives line newline character @ end you'll want remove well, such as:
if (strlen (line) > 0) if (line[strlen (line) - 1] == '\n') line[strlen (line) - 1] = '\0';
you should tokenising input little more intelligently, shell bash
(for example) has rather complex rules.
Comments
Post a Comment