这是我正在做的一组练习中的一个步骤。我编写的程序应该有两个以上的参数。第一个参数的使用尚未实现。其余参数是目录列表。
在这一步中,我要做的是为参数中给定的每个目录创建一个 cat 实例,使用 cat 获取每个目录的所有文件的内容并打印内容。我应该能够处理 /home/directory 和 /home/directory/ 之类的路径(最后一个 / 或没有)
目前我正在做的是尝试使用参数 /home/directory/* 运行 cat ,以便它读取给定目录中的所有文件并返回它们的内容。这是我的代码:
#include "Step1.h"
int main(int argc,char* argv[])
{
if(argc < 3)
{
printf("Usage: ./Step1 <exclusions file> <folder1> <folder2> <folder3> ...\n");
return -1;
}
int i;
for(i=2; i<argc; i++)
{
int catpipe[2];
if(pipe(catpipe))
{
printf("Error in pipe\n");
return -1;
}
pid_t pid = fork();
if(pid < 0)
{
printf("Error in fork\n");
return -1;
}
if(!pid)
{
dup2(catpipe[1],1); // cat pipe is used to get the output of cat program into this program.
close(catpipe[1]);
close(catpipe[0]);
char* args[3];
args[0] = "/bin/cat";
int length = strlen(argv[i]);
char* path;
if(argv[i][length - 1] != '/') // the path given does not have the ending /
{
path = malloc(length + 3);
strcpy(path,argv[i]);
path[length] = '/'; //append / at the end
path[length+1] = '*'; // append * at the end
path[length+2] = '\0';
}
else
{
path = malloc(length + 2); // the path contains the ending /
strcpy(path,argv[i]);
path[length] = '*'; // append * at the end
path[length+1] = '\0';
}
args[1] = path;
args[2] = NULL;
printf("%s\n",path);
execvp("/bin/cat",args);
}
close(catpipe[1]);
char buffer[200];
int total = read(catpipe[0],buffer,200); // read the output of cat program and print it.
buffer[total]='\0';
printf("The buffer contains: %s\n",buffer);
}
return 0;
}
我按如下方式运行此代码:
mod@mod-Inspiron-N5110:~/project$ ./Step1 exclusions ./testdirectory1 ./testdirectory2/
我得到的结果是:
/bin/cat: ./testdirectory1/*: No such file or directory
The buffer contains:
The buffer contains: ./testdirectory2/*
mod@mod-Inspiron-N5110:~/project$ /bin/cat: ./testdirectory2/*: No such file or directory
mod@mod-Inspiron-N5110:~/project$
但是当我这样做时:
mod@mod-Inspiron-N5110:~/project$ /bin/cat ./testdirectory1/*
结果是:
Testline 1 of testfile1 in testdirectory1
Test line 1 of testfile1 in testdirectory1
Testline 1 of testfile2 in testdirectory1
Testline 1 of testfile3 in testdirectory1
请帮助我用我的程序得到这个结果。
提前致谢