我有20个文本文件,我想使用matlab循环来获取每个文件的最后一行而不考虑其他行.是否有任何matlab命令来解决这个问题?
您可以尝试的一件事是将文本文件作为二进制文件打开,搜索到文件的末尾,并从文件末尾向后读取单个字符(即字节).此代码将从文件末尾读取字符,直到它遇到换行符(如果在文件的最末端找到换行符,则忽略换行符):
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
Run Code Online (Sandbox Code Playgroud)