Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

c - Reading a directory and checking if files are ascii

I am trying to read each file in a directory and check if it contains only ASCII characters, which means that if there is even non-ascii character in there it doesn't consider it.

#include <stdio.h>
#include <dirent.h>

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

        DIR *folder;
        int files = 0;
        struct dirent *entry;
        int flag = 0;
        int c;

        if(argc == 2){
                folder = opendir(argv[1]);
        }
        else{
                folder = opendir(".");
        }

        if(folder == NULL)
        {
                puts("Unable to read directory");
                return(1);
        }
        else
        {
                puts("Directory was opened!");
        }

        while( (entry=readdir(folder)) ){
                flag = 0;
                FILE *curr_file = fopen(entry->d_name,"r");
                while ((c = fgetc(curr_file)) != EOF){
                        if (c < 0 || c > 127){
                                break;
                                flag = 1;
                        }
                }
                if(flag == 0){
                        printf("ASCII file");
                }else{ printf("Not ASCII file"); }


        }
        closedir(folder);

        return 0;
}

For some reason though it doesn't work as intended and I can't really figure out why.

question from:https://stackoverflow.com/questions/65869598/reading-a-directory-and-checking-if-files-are-ascii

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...