When writing a text file reading function yourself, the first problem you will encounter is: for a given file name, how do you know that the disk file it represents is indeed a text file? Here is a very simple method: treat the given file as an untyped binary file, and then read each byte of the file sequentially. If there is a byte in the file with a value equal to 0, then this The file is not a text file; on the contrary, if no byte in the file has a value of 0, it can be determined that the file is a text file. This is the principle. Let’s take a look at how to program in Delphi to implement it -
Copy the code code as follows:
functionIsTextFile(FileName:string):boolean;
var
Fs:TFileStream;
i,size:integer;
IsTextFile:boolean;
ByteData:Byte;
begin
ifFileExists(FileName)then
begin
Fs:=TFileStream.Create(FileName,fmOpenRead);
IsTextFile:=true;
i:=0;
size:=Fs.Size;
While(i<size)andIsTextFiledo
begin
Fs.Read(ByteData,1);
IsTextFile:=ByteData<>0;
inc(i)
end;
Fs.Free;
Result:=IsTextFile
end
else
Result:=false
end;