试图从文件中读取

时间:2014-12-10 04:22:26

标签: c execvp

我正在尝试创建一个运行来自用户输入命令的程序 目前它适用于多个单词命令,但我试图实现重定向 我开始从文件中获取输入并且它无法正常工作,但我没有收到任何错误(我正在使用" wc -l< text.txt&#34进行测试;命令,text.txt文件是与程序相同的目录。)
这是代码:
- 输入是用户输入的str - 在使用此方法之前,我已经检查过它有重定向

redirect(int proc, char * input){
    char * comm;
    if(proc == 1){ //in
        comm = strsep(&input, "<");
    }
    else{ //out
        comm = strsep(&input, ">");
    }

    int proc2 = check(input);
    if(proc2 == 0){ //only one redirection
        if(proc == 1){ //in
            input = trim(input);
            int fd = open(input, O_RDWR);
            close(0);
            dup2(fd, 0);
            close(fd);

            comm = trim(comm);
            char ** words = parse(comm);

            char str[105];
            strcpy(str, "/bin/");
            strcat(str, words[0]);
            shrink(str);
            if(!execvp(str, words)){    /*exec failed */
                exit(1);
            }
        }
        else{ //out

        }
    }
    else{ //more than one redirection/pipe

    }
}

修改
我需要使用execvp命令来运行用户输入 用户命令&#34;&lt;&#34;需要将stdin更改为后面的文件。
我将stdin更改为text.txt,但我不知道如何将其作为arg传递,以便execvp可以运行它。

3 个答案:

答案 0 :(得分:0)

您尝试执行哪些类型的命令? 如果您的命令是dos命令,则可以在字符串变量中读取用户输入 ,以及何时想要执行该文件。创建一个bat文件然后执行它 通过以下代码

Process.Start(&#34;您的文件路径&#34;);

答案 1 :(得分:0)

如果仅执行用户指定的命令然后使用您执行shell命令,则可以使用system()调用。此函数将命令作为参数执行,并在命令shell上执行。您不需要创建任何单独的文件。

您可以将用户想要执行的命令作为字符串执行,然后将其作为参数传递给system()以执行它。 即

 system("wc -l < text.txt");

System()适用于Linux和Windows。

参考文献:Execute a Linux command in the c program

http://www.gnu.org/software/libc/manual/html_node/Running-a-Command.html

答案 2 :(得分:0)

经过大量的测试和研究后,我发现我使用的文件没有execvp从中读取文件所需的权限。
当我编写用于写入文件的代码然后尝试读取新创建的文件并且它工作时(在添加标志之后),我弄清楚了。
这是代码:

redirect(int proc, char * input){
    char * comm;
    if(proc == 1){ //in
        comm = strsep(&input, "<");
    }
    else{ //out
        comm = strsep(&input, ">");
    }

    int proc2 = check(input);
    if(proc2 == 0){ //only one redirection
        if(proc == 1){ //in
            input = trim(input);
            int fd = open(input, O_RDWR);
            close(0);
            dup2(fd, 0);
            close(fd);

            comm = trim(comm);
            char ** words = parse(comm);

            if(!execvp(words[0], words)){   /*exec failed */
                exit(1);
            }
        }
        else{ //out
            input = trim(input);
            int fd = open(input, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
            dup2(fd, 1);
            close(fd);

            comm = trim(comm);
            char ** words = parse(comm);

            if(!execvp(words[0], words)){   /*exec failed */
                exit(1);
            }
        }
    }
    else{ //more than one redirection/pipe

    }
}

所以我运行命令&#34; ls&gt;的text.txt&#34;并使用&#34; ls&#34;创建text.txt文件。结果然后运行&#34; wc -l&lt;的text.txt&#34;命令,它返回文件中的行。

相关问题