문제

Is there any way to check in Linux C if a file is a text file, e.g. UTF or ASCII? In bash, we have the program file. Is there any equivalent in C?

This is my function to validate a text file in C. I use popen, but it does not work fine. Sometimes I have an error in pclose. What would I need to edit in the code?

int check_file(char *path)
{
 FILE *file_type;
 char command[] = "/usr/bin/file";
 char command_to_execute[512];
 char check[512];
 int correct = 0;
 sprintf(command_to_execute,"%s %s",command,path);
 file_type = popen(command_to_execute,"r");
 if(file_type == NULL)
 {
   return correct;
 }
 fgets(check,512,file_type);
 char *pointer;
 pointer = strstr(check,"ASCII"); 
 if(pointer != NULL)
    correct = 1;
 pointer = strstr(check,"UTF");
 if(pointer != NULL)    
    correct = 1;          
 pclose(file_type);
 return correct;
}
도움이 되었습니까?

해결책

file is a program (not a bash function); you could read the file and check for non-ascii characters. If you find any output false and stop processing, if you reach the end of the file output true.

다른 팁

You can use libicu to test if a string matches a certain encoding. Iconv is another alternative

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top