2

I am trying to read the last line time value from a csv file. Check the following:

2018-07-26 11:04:00 1.17272 1.17275 1.17267 1.17272
2018-07-26 11:05:00 1.17272 1.17273 1.17265 1.17268
2018-07-26 11:06:00 1.17268 1.17273 1.17261 1.17264

The above is sample data. I have tried the following code and the result is as follows:

int file = FileOpen("latest.csv",FILE_READ|FILE_SHARE_READ|FILE_CSV|FILE_COMMON);
   if(file != INVALID_HANDLE)
   {
      FileSeek(file,-100,SEEK_END);

      while(!FileIsLineEnding(file))
      {
         Print(FileReadString(file));
      }
   }

   FileClose(file);

Output:

8-07-26 11:06:00
1.17268
1.17273
1.17261
1.17264

I m not getting the complete date value. Even if I try to increase the offset of the FileSeek() function.

Kindly, let me know how is it possible to read the csv file's last line.

Danny_ds
  • 11,201
  • 1
  • 24
  • 46
Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139

1 Answers1

1

I don't know mql5 but here's what I think the problem is:

  • The file is opened in csv mode (FILE_CSV), and it looks like FileReadString() reads a single field (not a full row) - just like FileReadNumber() reads a number from a column. So the function keeps reading separate fields until a newline is encountered (and the first field (date) is only read partial because of the offset).

From the docs:

When reading from a bin-file. the length of a string to read must be specified. When reading from a txt-file the string length is not required, and the string will be read from the current position to the line feed character "\r\n". When reading from a csv-file, the string length isn't required also, the string will be read from the current position till the nearest delimiter or till the text string end character.

So, instead of FILE_CSV, using FILE_TXT should read the whole line. Of course, you'll have to skip the first partial line (pos -100).

To read the full last line:

int file = FileOpen("latest.csv",FILE_READ|FILE_SHARE_READ|FILE_TXT|FILE_COMMON);

   if(file != INVALID_HANDLE)
   {
      FileSeek(file,-100,SEEK_END);

      // skip partial line
      FileReadString(file);

      // read last line
      Print(FileReadString(file));

      FileClose(file);
   }

To only read the last date you could still use CSV mode:

int file = FileOpen("latest.csv",FILE_READ|FILE_SHARE_READ|FILE_CSV|FILE_COMMON);

   if(file != INVALID_HANDLE)
   {
      FileSeek(file,-100,SEEK_END);

      // skip partial row
      while(!FileIsLineEnding(file))
      {
          FileReadString(file);
      }

      // read last date
      Print(FileReadString(file));
      // or maybe FileReadDatetime(file);

      FileClose(file);
   }

Also, FileClose() should be inside the if{} block.

Danny_ds
  • 11,201
  • 1
  • 24
  • 46