MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   Matlab命令访问每个文件的最后一行? (https://www.labfans.com/bbs/showthread.php?t=23329)

poster 2019-12-10 20:41

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



[B]回答:[/B]

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

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

[url=https://stackoverflow.com/questions/2659375]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 00:19

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.