-1

I am having a problem in reading CSV file using Delphi 5.

File contents are

1. a,b,c,d //1st line
2. ,,,,e,f //2nd line
3. n,d,e,f //3rd line
4. a,c,e //4th line

I am using following code to read

var
  respCSV : TStringList  ;
  sLine : string ;
  tf : TextFile;
begin
  respCSV := TStringList.Create ;
  // prompt the user for a file-name then load into a string list
  with openDialog1 do
  begin
    FileName := '';
    if Execute then
    begin
      AssignFile(tf, FileName);
      Reset(tf);
      while not eof(tf) do
      begin
        sLine := '' ;
        ReadLn(tf,sLine); //In Debug/Evaluate it shows 2nd row perfectly 
        showMessage(sLine); //but in showMessage Here 2nd row is showing as
        //null, While it has nulls only in start
        respCSV.Add(sLine); //Adding 2nd row as empty row

      end; //end while
    end;//end if
  end;//end with

2nd row in File starts with Null ,,,,e,f.. so it is showing all line as null

3
  • What do you mean by Null, is it character null ie #0? If that is the case, you must realize that #0 is considered as a string terminator. That's the reason why you get an empty string for second line. If I where you, I would find out why there are null characters in the CSV file, this seems not correct. You can filter out null characters from a string, here is a hint. Commented Mar 28, 2016 at 8:28
  • Yes, There is #0 i.e. the null terminator character. I exported this csv file from Survey Monkey. It is kinda survey response sheet in csv format. Commented Mar 28, 2016 at 10:15
  • Thanks... Filtering out null characters worked. Commented Mar 28, 2016 at 10:33

1 Answer 1

1

Your file is being read correctly. The string variable sLine holds the full line. However, ShowMessage treats a null character, #0, as being a terminator and does not display anything beyond that.

So, there is nothing (much) wrong with your code to read the file. Initialising sLine to the empty string is pointless since you assign it in the next line. And you don't close the file when you have finished reading it.

Sign up to request clarification or add additional context in comments.

2 Comments

respCSV.LoadFromFile(FileName); loads all four lines in a single line...i.e. respCSV.count result in 1 instead of 4
@DavidHeffernan: The TStrings.LoadFrom...() methods support bare-CR, bare-LF, and CRLF line breaks, and always have, even in Delphi 5 (I just checked). But what they don't support, and have never supported (even in modern versions), is embedded nulls. If LoadFrom...() encounters a null, it will stop loading and exit immediately. And since the second line starts with a null, only the first line gets loaded, that is why the Count is 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.