仅读取文本文件的最后一行 (C++ Builder)

only read last line of text file (C++ Builder)

有没有一种有效的方法来读取文本文件的最后一行?现在我只是用下面的代码阅读每一行。然后 S 保存读取的最后一行。有没有一种无需循环遍历整个文本文件即可获取最后一行的好方法?

TStreamReader* Reader;
Reader = new TStreamReader(myfile);
while (!Reader->EndOfStream) 
{
 String S = Reader->ReadLine();
}

正如 Remy Lebeau 评论的那样:

  1. 使用文件访问函数FileOpen,FileSeek,FileRead

    在此处查看用法示例:

  2. 将文件从末尾分块加载到内存中

    所以制作一个静态缓冲区并将文件从末尾分块加载到其中...

  3. 停在eol(行尾)通常CR,LF

    只需从块的末尾扫描 13,10 个 ASCII 码或它们的组合。当心一些文件的最后一行也终止了,所以你应该第一次跳过它...

    已知 eol 是:

    13
    10
    13,10
    10,13
    
  4. 构造线

    如果没有 eol 找到,则将整个块添加到字符串中,如果找到,则仅添加其后的部分 ...

这里是小例子:

int hnd,siz,i,n;
const int bufsz=256;                // buffer size
char buf[bufsz+1];
AnsiString lin;                     // last line output
buf[bufsz]=0;                       // string terminator
hnd=FileOpen("in.txt",fmOpenRead);  // open file
siz=FileSeek(hnd,0,2);              // obtain size and point to its end
for (i=-1,lin="";siz;)
    {
    n=bufsz;                        // n = chunk size to load
    if (n>siz) n=siz; siz-=n;
    FileSeek(hnd,siz,0);            // point to its location (from start)
    FileRead(hnd,buf,n);            // load it to buf[]
    if (i<0)                        // first time pass (skip last eol)
        {
        i=n-1; if (i>0) if ((buf[i]==10)||(buf[i]==13)) n--;
        i--;   if (i>0) if ((buf[i]==10)||(buf[i]==13)) if (buf[i]!=buf[i+1]) n--;
        }
    for (i=n-1;i>=0;i--)            // scan for eol (CR,LF)
     if ((buf[i]==10)||(buf[i]==13))
      { siz=0; break; } i++;        // i points to start of line and siz is zero so no chunks are readed after...
    lin=AnsiString(buf+i)+lin;      // add new chunk to line
    }
FileClose(hnd);                     // close file
// here lin is your last line