有没有一种刷新目录指针的方法?

时间:2018-10-19 18:32:03

标签: c fork fflush

我正在尝试使用fork对目录中的文件进行排序。我有我的mergesort代码,但是在实现它之前,我试图弄清楚如何使用fork。

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include "scannerCSVsorter.h"

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

    char buffer[100];
    getcwd(buffer,100);
    traverse(buffer);

    return 0;
}

void traverse(char *name){

    DIR *direc;
    struct dirent *dirent_n;    

    direc = opendir(name);
    chdir(name);

    while((dirent_n = readdir(direc)) != NULL){        
        if(isDir(dirent_n->d_name) != 0){
            if(!strcmp(dirent_n->d_name,".") || !strcmp(dirent_n- 
            >d_name,"..")){ //avoid the current and parent directory
                continue;
            }
            printf("%s is a directory\n", dirent_n->d_name);
            fork();
            printf("%d\n", getpid());
            if(getpid() == -1){
                printf("failure to create child\n");
                return;
            }
            traverse(dirent_n->d_name);
        }
        else{
            pid_t child = fork();
            if(getpid() == -1){
                printf("failure to create child\n");                
                return;
            }
            if(getpid() == child){
                printf("%s is a file\n", dirent_n->d_name);
                return;
            }

        }

    }
    return;
}

int isDir(char name[]){
    struct stat state;
    if(stat(name, &state) != 0)
        return 0;
    return S_ISDIR(state.st_mode);
}

这是我的输出

-Movie_megadata is a directory
-Movie_megadata is a directory
-7715
-7716
-7717
-7718
-number 2 is a directory
-number 2 is a directory
-number 2 is a directory
-number 2 is a directory
-7715
-7720
-7723
-number 2 is a directory
-7719
-7728
-7726
-7727
-7721
-number 2 is a directory
-number 2 is a directory
-number 2 is a directory
-number 2 is a directory
-number 2 is a directory
-number 2 is a directory
-number 2 is a directory
-7716
-7718
-7736
-7717
-7730
-7725
-number 2 is a directory
-7731
-number 2 is a directory
-7729
-number 2 is a directory
-7739
-7735
-7740
-7738
-7732
-7742
-7741
-7722
-7733
-number 2 is a directory
-7744
-7724

我认为这是由于不刷新指针并且fork重新启动了循环。我已经尝试过fflush(stdout),但是遇到了同样的错误。有没有一种刷新目录指针的方法。

0 个答案:

没有答案