[ACCEPTED]-How do you get the size of a file in MATLAB?-file-io
Please see the dir function as stated above.
Please 2 note that the dir function works on files 1 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 5 information, which includes the sizes of 4 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 3 you are looking for only one file, you can 2 do what Elazar said and just pass an absolute 1 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 1 Objects:
myFile = java.io.File('filename_here')
flen = length(myFile)
If you don't want to hardcode in your directory, you 3 can use the built in pwd tool to find the 2 current directory and then add your file 1 name to it. See example below:
FileInfo = dir([pwd,'\tempfile.dat'])
FileSize = FileInfo.bytes
The question seems to indicate that fopen
/fread
/.. is 4 used. In this case, why not seeking to the 3 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 2 could have provided a shortcut..
More on 1 ftell
can be found here.
This code works for any file and directory 1 (no need for absolute path) :
dirInfo=dir(pwd);
index = strcmp({dirInfo.name},[filename, '.ext']); % change the ext to proper extension
fileSize = dirInfo(index).bytes
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.