Recent

Author Topic: String in binary file  (Read 223 times)

Dzandaa

  • Sr. Member
  • ****
  • Posts: 360
  • From C# to Lazarus
String in binary file
« on: October 05, 2024, 12:14:46 pm »
Hello
I have a binary file that contains ASCII strings in some places.
Does anyone have an idea of a function like:
Code: Pascal  [Select][+][-]
  1. function StringInFile(File: String; Text: String): boolean;

To search if "Text" exist in "File"?

Thank you.

B->
Regards,
Dzandaa

d4eva

  • New Member
  • *
  • Posts: 26
Re: String in binary file
« Reply #1 on: October 05, 2024, 12:55:21 pm »
Here's very simple implementation.

Code: Pascal  [Select][+][-]
  1. function StringInFile(FileName: string; Text: ansistring): boolean;
  2. var
  3.   s: ansistring;
  4.   f: TFileStream;
  5. begin
  6.   f := TFileStream.Create(FileName, fmOpenRead);
  7.   try
  8.     SetLength(s, f.Size);
  9.     f.Read(s[1], f.Size);
  10.     Result := Pos(Text, s) > 0;
  11.   finally
  12.     f.Free;
  13.   end;
  14. end;    

Thaddy

  • Hero Member
  • *****
  • Posts: 15929
  • Censorship about opinions does not belong here.
Re: String in binary file
« Reply #2 on: October 05, 2024, 12:59:02 pm »
Posts crossed, but here's a slight variation:
Code: Pascal  [Select][+][-]
  1. function StringInFile(const aFile,aText: String): boolean;
  2. var
  3.   s:TStringList;
  4. begin
  5.   Result := False;
  6.   s:= TStringList.Create;
  7.   try
  8.     s.LoadFromFile(aFile);
  9.     if Pos(aText,s.text) > 0 then result := true;
  10.   finally
  11.     s.Free;
  12.   end;
  13. end;
Both options are not really suited for very large files > available memory.

It is not good practise to have the parameters named as internal types, file and text are Pascal built-in types.
« Last Edit: October 05, 2024, 01:10:54 pm by Thaddy »
If I smell bad code it usually is bad code and that includes my own code.

Dzandaa

  • Sr. Member
  • ****
  • Posts: 360
  • From C# to Lazarus
Re: String in binary file
« Reply #3 on: October 05, 2024, 03:54:51 pm »
Hi,

@Thaddy.

Quote
It is not good practice to have the parameters named as internal types, file and text are Pascal built-in types.

I know, never do that, just an example.

@d4eva

 Thank you, it's working.

B->
« Last Edit: October 05, 2024, 03:57:23 pm by Dzandaa »
Regards,
Dzandaa

 

TinyPortal © 2005-2018