Spacey
Spacey

Reputation: 3011

Find out how many samples in a *.bin or *.dat file exist, before reading it in MATLAB

I am trying to figure out how I can tell, in MATLAB, how many samples exist in a given *.bin or *.dat file, before I go ahead and read it.

Obviously, I know the data type, (float, int16, etc) before hand.

I know that I can use something like:

fid = fopen('foo.bin', 'r');
data = fread(fid, inf, 'int16');
fclose(fid);

, and this code will read ALL the samples in, but the problem is that I want to know how big the file is to begin with, so that I can divvy up how to read it it. The files I am dealing with are humungous and I cannot use inf. (Or if I can, it takes forever).

So to summarize, I would like to be able to find a way to be able to tell, through MATLAB, how many samples (of a specified type) I have in my *.bin file, so that I can decide how to divide it up.

Thanks!

Upvotes: 0

Views: 265

Answers (2)

Steve
Steve

Reputation: 4097

You can tell the size of the file from the directory listing. The function dir(...) returns the number of bytes in the file:

filename = 'foo.bin';

tooBig = 1e6;
fileInfo = dir(filename);
bytesInMyFile = fileInfo.bytes;

if bytesInMyFile > tooBig
    disp('File is Too Big!');
end

Upvotes: 3

Spacey
Spacey

Reputation: 3011

Ok, so the answer is the following:

BytesPerSample = 4;  %for example
fid = fopen('foo.bin', 'r');
fseek(fid, 0, 'eof');
pos = ftell(fid);
fclose(fid);
NumSamples = pos / ByesPerSample;

Then from here on out I can divy up the file as I want. :-)

Upvotes: 1

Related Questions