Is there a way in Matlab to determine the number of lines in a file without looping through each line?

后端 未结 5 1670
無奈伤痛
無奈伤痛 2020-12-05 00:57

Obviously one could loop through a file using fgetl or similar function and increment a counter, but is there a way to determine the number of lines in a file without

5条回答
  •  旧巷少年郎
    2020-12-05 01:10

    I think a loop is in fact the best - all other options so far suggested either rely on external programs (need to error-check; need str2num; harder to debug / run cross-platform etc.) or read the whole file in one go. Loops aren't so bad. Here's my variant

    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
    

    EDIT: Jonas rightly points out that the above loop is really slow. Here's a faster version.

    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
    

    It's still not as fast as wc -l, but it's not a disaster either.

提交回复
热议问题