检查文件是否为C中的纯文本。

时间:2021-07-10 21:21:51

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 function file. Is there any equivalent in C?

如果文件是文本文件,例如UTF或ASCII,是否有办法检查Linux C ?在bash中,我们有函数文件。在C中是否有等价的?

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

编辑:这是我在c中验证一个文本文件的函数。我使用popen,但是它不工作。有时在pclose中有一个错误。需要在代码中编辑什么?

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;
}

2 个解决方案

#1


3  

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.

文件是一个程序(不是bash函数);您可以读取文件并检查非ascii字符。如果您发现任何输出错误和停止处理,如果您到达文件输出的末端为真。

#2


0  

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

您可以使用libicu来测试字符串是否匹配某种编码。Iconv是另一个选择

#1


3  

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.

文件是一个程序(不是bash函数);您可以读取文件并检查非ascii字符。如果您发现任何输出错误和停止处理,如果您到达文件输出的末端为真。

#2


0  

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

您可以使用libicu来测试字符串是否匹配某种编码。Iconv是另一个选择