Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Testing for invalid chars

Status
Not open for further replies.

AP81

Programmer
Apr 11, 2003
740
AU
Hi,

I have made a small utility for my work which tests hard drives (FAT32) for corruption.

Some of the corrupt hard drives contain filenames with invalid characters. I basically want to compare a string to a list of invalid characters to assess whether a file is invalid or not.

e.g.
Filename = '?#n120.mp3';
List of invalid characters = '/,\,:,#,?,",<,>,|';

if filename <> contain invalid character then passed := true
else passed = false.

This is the way I'm doing it (which seems pretty hack). Is there a better way?

Code:
  private
    { Private declarations }
    function isValidFile(name:string):boolean;  
...
var
invalid_chars : TStringList; //global

...

function TfrmCorruptionTest.isValidFile(name:string):boolean;
var
 i,j : integer;
 CharToCheck : ShortString;
begin
  i:=Length(name);
  for j := 0 to i do
    begin
      CharToCheck := Copy(name,j,1);
      if invalid_chars.IndexOf(CharToCheck) <> -1 then
        begin
          result := false;  //filename is invalid
          exit;
        end;
    end;
  result := true;           //filename is valid
end;

procedure TfrmCorruptionTest.Button1Click(Sender: TObject);
var
 FileNameToCheck : string;
begin
  FileNameToCheck := '?#n120.mp3';
  //FileNameToCheck := 'aaacccdd';
  if IsValidFile(FileNameToCheck) then showMessage('Valid')
  else ShowMessage('Invalid');
end;


procedure TfrmCorruptionTest.FormCreate(Sender: TObject);
begin
  //create list
  invalid_chars := TStringList.Create;
  //add invalid chars
  invalid_chars.Add('\');
  invalid_chars.Add('\');
  invalid_chars.Add('/');
  invalid_chars.Add(':');
  invalid_chars.Add('#');
  invalid_chars.Add('?');
  invalid_chars.Add('"');
  invalid_chars.Add('<');
  invalid_chars.Add('>');
  invalid_chars.Add('|');
end;

procedure TfrmCorruptionTest.FormDestroy(Sender: TObject);
begin
  invalid_Chars.Free;
end;

Any help or tips are appreciated.
Thanks.




------------------------------------
There's no place like 127.0.0.1
------------------------------------
 
Actually the perfect tool for this would be to create a set for the task.

Then something like (if my memory serves me right):

var
invalid_char_list: set of char;

function valid_file(instr: string): boolean;
var
i: integer;
tag: boolean;
begin
tag := true;
for i := 1 to length(instr) do
if instr in invalid_char_list then
tag := false;
valid_file := tag;
end.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top