将控制台输出更改为C中的文件时出错

时间:2017-04-21 08:35:16

标签: c linux

我是新堆栈溢出所以忍受我:) 我正在尝试创建一个自定义Linux shell作为项目。 现在我想在用户使用>时将默认输出转到文件而不是控制台。符号例如ls> FILENAME.TXT 但是,程序崩溃并弹出错误地址错误,但它将命令输出写入文件。

    #include <sys/wait.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <errno.h>
    #include <fcntl.h>
    typedef char* string;





     int main (int argc,char** argv) {

      int error = 0;

  int posIn=0; int posOut=0; int appendMark=0; 
  string Output,Input;

while (1) { 
error=0;
char progName[255];
printf("\nmysh3 > ");


 if(fgets(progName,500,stdin)==NULL){return 0 ;}
char dir[1024];
string params[40];
string pch=progName;
int i=0;

      while ((pch = strtok (pch," \n")) != NULL){
        params[i]=pch;
        if (strcmp(pch,"<")==0) { posIn = i;params[i]=NULL;i--;} // < is       skipped and we put only the name of the command on the params array
        if (strcmp(pch,">")==0) { posOut = i;params[i]=NULL;i--;} //output 
         if (strcmp(pch,">>")==0) {appendMark=1;params[i]=NULL;i--;}
        i++;

         pch = NULL;
      }



params[i]=NULL;





if(strlen(progName)>255){
    printf("The commands can't be over 255 characters\n");
    return 0;
}



        if (posOut) {

            int out = open(params[posOut], O_CREAT|O_TRUNC|O_WRONLY, 0777);
            params[posOut]=NULL;
        if (out < 0) {
            error = 1;
             fprintf(stderr,"open error: %d [%s]\n",errno,strerror(errno));
            exit(1); }

        int k = dup2(out,1);
        if (k<0) {
            error = 1;
            perror("Cannot redirect output");
            }

        close(out);
        }


pid_t proccess1,waitpid;
int status;

proccess1 = fork();

    if (proccess1<0) {perror("Out of memory"); } //Monos tropos na apotyxei h fork einai na mhn yparxei mnhmh
    else if (proccess1==0) {

     execvp(params[0],params);

        if (!error) {perror("Unknown command");}
         }  
    else { 
        waitpid=wait(&status);
        if (waitpid==-1) {perror("ERROR: A NEW ZOMBIE IS BORN 3:)");return 0;}
        }



}



    return 0; }

0 个答案:

没有答案