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
.
Check if a file is plain text in C
Question
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;
}
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow