2010-04-17 68 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); 
相關問題