【问题标题】:Matlab command to access the last line of each file?Matlab命令访问每个文件的最后一行?
【发布时间】:2013-04-17 01:07:28
【问题描述】:

我有 20 个文本文件,我想使用 matlab 循环来获取每个文件的最后一行,而不考虑其他行。有什么matlab命令可以解决这个问题吗?

【问题讨论】:

  • 每个文件的行数不一样,可以是随机的。

标签: file matlab


【解决方案1】:

您可以尝试的一件事是将文本文件作为二进制文件打开,查找文件末尾,然后从文件末尾向后读取单个字符(即字节)。此代码将从文件末尾读取字符,直到遇到换行符(如果在文件末尾找到换行符,则忽略换行符):

fid = fopen('data.txt','r');     %# Open the file as a binary
lastLine = '';                   %# Initialize to empty
offset = 1;                      %# Offset from the end of file
fseek(fid,-offset,'eof');        %# Seek to the file end, minus the offset
newChar = fread(fid,1,'*char');  %# Read one character
while (~strcmp(newChar,char(10))) || (offset == 1)
  lastLine = [newChar lastLine];   %# Add the character to a string
  offset = offset+1;
  fseek(fid,-offset,'eof');        %# Seek to the file end, minus the offset
  newChar = fread(fid,1,'*char');  %# Read one character
end
fclose(fid);  %# Close the file

【讨论】:

    【解决方案2】:

    在 Unix 上,只需使用:

    [status result] = system('tail -n 1 file.txt');
    if isstrprop(result(end), 'cntrl'), result(end) = []; end
    

    在 Windows 上,您可以从 GnuWin32UnxUtils 项目中获取 tail 可执行文件。

    【讨论】:

      【解决方案3】:

      它可能效率不高,但对于短文件来说就足够了。

      function pline = getLastTextLine(filepath)
      fid = fopen(filepath);
      
      while 1
          line = fgetl(fid);
      
          if ~ischar(line)
              break;
          end
      
          pline = line;
      end
      fclose(fid);
      

      【讨论】:

        猜你喜欢
        • 2014-04-14
        • 1970-01-01
        • 2011-05-19
        • 2020-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-30
        • 2019-08-04
        相关资源
        最近更新 更多