各位,我需要读取一个UNIX文本文件,
但是因为UNIX换行符和WINDOW下的不一样,所以总是把整个文件当成一行读取。我想一行一行的读出来,请大家帮帮我。谢谢

解决方案 »

  1.   

    读到#10就认为是行尾了, 这样不管UNIX还是WINDOWS都能读到整行
      

  2.   

    问个弱智问题:怎么读?
    请给两行代码,好吗?我初学DELPHI
      

  3.   

    用tstringlist.loadfromfile就可以了
      

  4.   

    你要的大概就是这种函数吧:var
      RestStr: string = '';    // 记录上次读到的半行内容function ReadOneLine(FileHandle: Integer): string;   // FileHandle是用FileOpen打开文件所返回的句柄
    var
      buf: array [0..1024] of char;  // 分块读, 每次读1k
      i, l: Integer;
    begin
      repeat
        l := FileRead(FileHandle, buf, 1024);
        if l > 0 then
        begin
          buf[l] := #0;                     // 末尾添加#0, 这样可以供delphi直接把Buf转换成string
          for i := 0 to l - 1 do
            if buf[i] = #10 then            // 读到行尾了
            begin
              buf[i] := #0;
              Result := RestStr+buf;
              RestStr := pchar(@buf[i+1]);  // 剩下的保存到RestStr中供下次读时拼成整行
              if Result[Length(Result)] = #13 then  // windows的换行符, 行数据中多读了一个#13, 需去掉
                Result := copy(Result, 1, Length(Result)-1);
              exit;
            end
            else RestStr := RestStr+buf;
        end;
      until l <= 0;
    end;
      

  5.   

    上面的程序有bug, 改了一下, 应该没问题了:var
      RestStr: string = '';    // 记录上次读到的半行内容function ReadOneLine(FileHandle: Integer): string;   // FileHandle是用FileOpen打开文件所返回的句柄
    var
      buf: array [0..1024] of char;  // 分块读, 每次读1k
      i, l: Integer;
    begin
      l := pos(#10, RestStr);
      if l > 0 then
      begin
        result := copy(RestStr, 1, l-1);
        delete(RestStr, 1, l);
        exit;
      end;
      repeat
        l := FileRead(FileHandle, buf, 1024);
        if l > 0 then
        begin
          buf[l] := #0;                     // 末尾添加#0, 这样可以供delphi直接把Buf转换成string
          for i := 0 to l - 1 do
            if buf[i] = #10 then            // 读到行尾了
            begin
              buf[i] := #0;
              Result := RestStr+buf;
              RestStr := pchar(@buf[i+1]);  // 剩下的保存到RestStr中供下次读时拼成整行
              if Result[Length(Result)] = #13 then  // windows的换行符, 行数据中多读了一个#13, 需去掉
                Result := copy(Result, 1, Length(Result)-1);
              exit;
            end
            else RestStr := RestStr+buf;
        end;
      until l <= 0;
    end;