2010-04-17 17 views
5

我有20个文本文件,我想使用matlab循环来获取每个文件的最后一行,而不考虑其他行。有没有任何matlab命令来解决这个问题?Matlab命令来访问每个文件的最后一行?

+0

每个文件中的行数不相同,可以是随机的。 – bzak 2010-04-17 18:06:06

回答

5

你可以尝试的一件事是打开文本文件作为二进制文件,寻找到文件的末尾,并从文件的末尾向后读取单个字符(即字节)。直到碰到一个换行符(忽略换行,如果它发现它在文件的末尾)这段代码从文件中读取的结束字符:

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 
3

在Unix平台上,只需使用:

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

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

2

它可能不是很有效,但对于短文件来说就足够了。

function pline = getLastTextLine(filepath) 
fid = fopen(filepath); 

while 1 
    line = fgetl(fid); 

    if ~ischar(line) 
     break; 
    end 

    pline = line; 
end 
fclose(fid);