显然,可以使用fgetl或类似函数循环访问文件并递增计数器,但有没有办法确定文件中的行数而不用进行这样的循环?
答案 0 :(得分:30)
我喜欢使用以下代码来完成此任务
fid = fopen('someTextFile.txt', 'rb');
%# Get file size.
fseek(fid, 0, 'eof');
fileSize = ftell(fid);
frewind(fid);
%# Read the whole file.
data = fread(fid, fileSize, 'uint8');
%# Count number of line-feeds and increase by one.
numLines = sum(data == 10) + 1;
fclose(fid);
如果你有足够的内存来一次读取整个文件,它会非常快。它应该适用于Windows和Linux风格的行结尾。
编辑:我衡量了目前为止提供的答案的效果。以下是确定包含100万个double值(每行一个值)的文本文件的行数的结果。平均10次尝试。
Author Mean time +- standard deviation (s)
------------------------------------------------------
Rody Oldenhuis 0.3189 +- 0.0314
Edric (2) 0.3282 +- 0.0248
Mehrwolf 0.4075 +- 0.0178
Jonas 1.0813 +- 0.0665
Edric (1) 26.8825 +- 0.6790
使用Perl并将所有文件作为二进制数据读取的方法最快。我不会感到惊讶,如果Perl在内部也同时读取文件的大块而不是逐行循环(只是一个猜测,对Perl一无所知)。
使用简单的fgetl()
- 循环比其他方法慢25-75倍。
编辑2:包括Edric的第二种方法,它比更多更快,与Perl解决方案相媲美,我会说。
答案 1 :(得分:15)
我认为循环实际上是最好的 - 到目前为止所有其他选项建议要么依赖外部程序(需要错误检查;需要str2num;更难调试/运行跨平台等)或读取整个文件一气呵成。循环不是那么糟糕。这是我的变种
function count = countLines(fname)
fh = fopen(fname, 'rt');
assert(fh ~= -1, 'Could not read: %s', fname);
x = onCleanup(@() fclose(fh));
count = 0;
while ischar(fgetl(fh))
count = count + 1;
end
end
编辑:Jonas正确地指出上述循环非常缓慢。这是一个更快的版本。
function count = countLines(fname)
fh = fopen(fname, 'rt');
assert(fh ~= -1, 'Could not read: %s', fname);
x = onCleanup(@() fclose(fh));
count = 0;
while ~feof(fh)
count = count + sum( fread( fh, 16384, 'char' ) == char(10) );
end
end
它仍然没有wc -l
那么快,但它也不是灾难。
答案 2 :(得分:12)
我找到了一个很好的技巧here:
if (isunix) %# Linux, mac
[status, result] = system( ['wc -l ', 'your_file'] );
numlines = str2num(result);
elseif (ispc) %# Windows
numlines = str2num( perl('countlines.pl', 'your_file') );
else
error('...');
end
其中'countlines.pl'
是perl脚本,包含
while (<>) {};
print $.,"\n";
答案 3 :(得分:4)
您可以一次阅读整个文件,然后计算您已阅读的行数。
fid = fopen('yourFile.ext');
allText = textscan(fid,'%s','delimiter','\n');
numberOfLines = length(allText{1});
fclose(fid)
答案 4 :(得分:0)
我建议使用外部工具。例如,名为cloc
的应用,您可以免费下载here。
在Linux上,您只需输入cloc <repository path>
并获取
YourPC$ cloc <directory_path>
87 text files.
81 unique files.
23 files ignored.
http://cloc.sourceforge.net v 1.60 T=0.19 s (311.7 files/s, 51946.9 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
MATLAB 59 1009 1074 4993
HTML 1 0 0 23
-------------------------------------------------------------------------------
SUM: 60 1009 1074 5016
-------------------------------------------------------------------------------
他们还声称它应该适用于Windows。