c-这个程序对文件进行word包装,希望添加一个功能,如果我提供了一个文件目录,并且其中有另一个文件,也可以包装这些文件



所以基本上当用户在命令行中输入时/ww-r10(目录名(我希望它对指定目录中的任何内容进行换行,并检查该目录中是否有子目录,并对其进行换行。。。。我卡住了。。。我知道de type==8给了我一个文件类型,但我不确定之后该怎么办,。。。。我试图使它递归,现在它与第一部分完美地配合。如果我提供一个目录或文件,它会将所有这些文件用词包装在那里,但是我似乎不知道如何检查文件夹是否有子目录,我认为我编码它的方式只会真正工作一次,以检查它是否是子目录,因为如果该子目录有一个包含更多文件等的子目录,该怎么办?我要创建一个函数吗?我要开始pthread吗?是否可以在if语句中创建pthread?C编程

if(argc  == 3 || argc==4) {
if(argv[1][0]=='-'&& argv[1][1]=='r'){
file_width=atoi(argv[2]);
printf("Entered file with with the speical 'R' command is: %dn",file_width);
dir = opendir(argv[3]);
while ((de = readdir(dir))) {
if(de->d_name[0] == '.' || (strncmp(de->d_name,"wrap",4) == 0)) {
if (DEBUG) printf("File ignored.n");
continue;                                                                   // ignore (.) and already wrapped files
}
if(de->d_type==8){

}
char s[270] = "wrap.";                                                          // temporary string for output file
chdir(argv[3]);
fd_in = open(de->d_name, O_RDONLY);                                             // read current file in the directory
fd_out = open(strcat(s,de->d_name),O_RDWR|O_CREAT|O_APPEND | O_TRUNC, 0600);    // create output file

if (DEBUG) printf("Current file name is: %sn", de->d_name);


word_wrap(fd_in,fd_out);
close(fd_in);
close(fd_out);
}

}

你已经说过你正在尝试使这个递归,所以简单的答案是">我做一个函数吗";是";是的";。这个函数本质上包含了从opendir行到块末尾的代码,并进行了一些调整,特别是当前工作目录的更改和递归函数调用,例如:

void wrapdir(const char *dirname)
{
if (chdir(dirname) != 0) { perror(dirname); return; }   // minimal error check
DIR *dir = opendir(".");
struct dirent *de;
int fd_in, fd_out;
while (de = readdir(dir))
{
if (de->d_name[0] == '.' || strncmp(de->d_name, "wrap", 4) == 0)
{
if (DEBUG) printf("File ignored.n");
continue;
}
if (de->d_type == DT_DIR) { wrapdir(de->d_name); continue; }
char s[270] = "wrap.";
fd_in = open(de->d_name, O_RDONLY);
fd_out = open(strcat(s, de->d_name), O_RDWR|O_CREAT|O_APPEND|O_TRUNC, 0600);
if (DEBUG) printf("Current file name is: %sn", de->d_name);
word_wrap(fd_in, fd_out);
close(fd_in);
close(fd_out);
}
closedir(dir);
chdir("..");
}

(由于您已经使用了具有已知值的d_type成员,因此您显然对在GNU/Linux等系统上运行的代码感到满意,在这些系统中可以使用此扩展,但请注意,只有一些文件系统完全支持它。(

上述函数最初可以通过用替换main中移动的代码来调用

wrapdir(argv[3]);

相关内容

最新更新