LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 943|回复: 1

求助:怎样实现cd 命令

[复制链接]
发表于 2006-3-8 17:33:53 | 显示全部楼层 |阅读模式
现在要用C写一个shell,我就直接使用popen了,但是
发现cd命令不能改变当前路径,应该使用什么方式呢
下面是我的代码
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define commandLength 4096
void HandleCommand(char *command)
{
   FILE *read_fp;
   char buffer[4096];
   int chars_read;
   memset(buffer,'\0',sizeof(buffer));
   read_fp=popen(command,"r");
   if(read_fp!=NULL)
    {
       chars_read=fread(buffer,sizeof(char),4096,read_fp);
       if(chars_read>0)
        {  
           printf("\n%s",buffer);
         }
         pclose(read_fp);
         return;
     }
  printf("命令错误输入\n");
  return;

}   
int main()
{
   char * temp;
    printf("##############欢迎进入刘昕的shell########### \nliuxin's shell&&:   ");
    char inputcommand[commandLength];
     while(1)
     {
      fgets(inputcommand,commandLength,stdin);
      if(strcmp(inputcommand,"exit\n")==0) {
         printf("您已经正常退出本shell\n");
          return 1;
         }
     temp=strtok(inputcommand," ");
     if(strcmp(temp,"cd")==0) //使用外部函数chdir控制当前目录
        { temp =strtok(NULL, " ");
          chdir(temp);
          system(inputcommand);
          }
      
      else
            HandleCommand(inputcommand);
      printf("\nliuxin's shell&&:  ");
     }
}
发表于 2006-3-8 19:42:12 | 显示全部楼层
[php]
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define commandLength 4096
void HandleCommand(char *command)
{
   FILE *read_fp;
   char buffer[4096];
   int chars_read;
   memset(buffer,'\0',sizeof(buffer));
   read_fp=popen(command,"r");
   if(read_fp!=NULL)
    {
       chars_read=fread(buffer,sizeof(char),4096,read_fp);
       if(chars_read>0)
        {  
           printf("\n%s",buffer);
         }
         pclose(read_fp);
         return;
     }
  printf("命令错误输入\n");
  return;

}   
int main()
{
   char * temp;
    printf("##############欢迎进入刘昕的shell########### \nliuxin's shell&&:   ");
    char inputcommand[commandLength];
     while(1)
     {
      fgets(inputcommand,commandLength,stdin);
      if(strcmp(inputcommand,"exit\n")==0) {
         printf("您已经正常退出本shell\n");
          return 1;
         }
     temp=strtok(inputcommand," ");
     if(strcmp(temp,"cd")==0) //使用外部函数chdir控制当前目录
        { temp =strtok(NULL, " ");

////////////////////////////////////////////////////////////////////
          temp[strlen(temp)-1] = 0;
//////////////////////////////////////////////////////////////////////

          chdir(temp);
          system(inputcommand);
          }
      
      else
            HandleCommand(inputcommand);
      printf("\nliuxin's shell&&:  ");
     }
}[/php]
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表