How do you get the size of a file in MATLAB?

What is the best way to figure out the size of a file using MATLAB? The first thought that comes to mind is size(fread(fid)).

Answers


Please see the dir function as stated above.

Please note that the dir function works on files and not on directories only.

>> s = dir('c:\try.c')

s = 

       name: 'try.c'
       date: '01-Feb-2008 10:45:43'
      bytes: 20
      isdir: 0
    datenum: 7.3344e+005

You can use the DIR function to get directory information, which includes the sizes of the files in that directory. For example:

dirInfo = dir(dirName);  %# Where dirName is the directory name where the
                         %#   file is located
index = strcmp({dirInfo.name},fileName);  %# Where fileName is the name of
                                          %#   the file.
fileSize = dirInfo(index).bytes;  %# The size of the file, in bytes

Or, since you are looking for only one file, you can do what Elazar said and just pass an absolute or relative path to your file to DIR:

fileInfo = dir('I:\kpe\matlab\temp.m');
fileSize = fileInfo.bytes;

Use the fact that MatLab has access to Java Objects:

myFile = java.io.File('filename_here')
flen = length(myFile)

If you don't want to hardcode in your directory, you can use the built in pwd tool to find the current directory and then add your file name to it. See example below:

FileInfo = dir([pwd,'\tempfile.dat'])
FileSize = FileInfo.bytes

The question seems to indicate that fopen/fread/.. is used. In this case, why not seeking to the end of the file and reading the position?

Example:

function file_length = get_file_length(fid)
% extracts file length in bytes from a file opened by fopen
% fid is file handle returned from fopen

% store current seek
current_seek = ftell(fid);
% move to end
fseek(fid, 0, 1);
% read end position
file_length = ftell(fid);
% move to previous position
fseek(fid, current_seek, -1);

end

Matlab could have provided a shortcut..

More on ftell can be found here.


This code works for any file and directory (no need for absolute path) :

    dirInfo=dir(pwd);
    index = strcmp({dirInfo.name},[filename, '.ext']); % change the ext to proper extension 
    fileSize = dirInfo(index).bytes

Easy way to find size of file is: enter these cammands

K=imfinfo('filename.formate');

size_of_file=K.FileSize

and get size of file.


Need Your Help

Is there a way to change context to iframe in javascript console?

javascript iframe console firebug

I would like to change the context of the javascript executed in the webkit developer tool/firebug console to execute its code like it is running from inside an iframe on the page.

Shortest way to slice even/odd lines from a python array?

python arrays

Or, a more general question would be, how to slice an array to get every n-th line, so for even/odd you'd want to skip one line, but in the general case you'd want to get every n-th lines, skipping...