Error while reading files from a directory

1 回表示 (過去 30 日間)
Cole
Cole 2011 年 2 月 14 日
Here is my code:
awdFiles = dir(fullfile(uigetdir,'*.awd'))
for k = 1:length(awdFiles)
waveform = awdFiles(k).name
fid = fopen(waveform)
A(:,k) = textscan(fid, '%s')
fclose(fid);
end
I am recieving this error:
fid =
-1
??? Error using ==> textscan Invalid file identifier. Use fopen to generate a valid file identifier.
Error in ==> readintest at 8 A(:,k) = textscan(fid, '%s')
The thing I do not understand is when say I have 3 files with the names:
DC282 Ch1.awd DC282 Ch1test2.awd DC282 Ch1test3.awd
The code works fine and reads in each file no problem.
If the names are:
DC282 Ch1.awd DC282 Ch1test2.awd DC282 Ch2.awd
The program throws the error out when trying to open the Ch2 file. It seems the names of the files are giving it issues and I am unsure why. I do not see why it has a problem because it pulls the name of the file correctly, but can't open it. Am I missing something simple? Do I need to reinitialize the waveform variable everytime or something?
Thanks

採用された回答

Jiro Doke
Jiro Doke 2011 年 2 月 14 日
It's probably the directory. Are the files in a different directory than where you're running from? Store the directory name and use the full path:
dirname = uigetdir;
awdFiles = dir(fullfile(dirname,'*.awd'))
for k = 1:length(awdFiles)
waveform = fullfile(dirname, awdFiles(k).name)
fid = fopen(waveform)
A(:,k) = textscan(fid, '%s')
fclose(fid);
end
  2 件のコメント
Cole
Cole 2011 年 2 月 14 日
Thanks man, that did it. Care to explain why? Im guessing the directory wasn't getting carried through the for loop everytime? and just the first time?
Jiro Doke
Jiro Doke 2011 年 2 月 14 日
I'm actually not sure why it worked the first time. Unless you happen to have a file with the same name as the first file somewhere on the MATLAB path.
Try typing "which <filename>" where <filename> is the name of the first .awd file.
If you type "awdFiles.name" on the command line, you'll see that it only shows the file names, not the full path. So you always have to reconstruct the full path using the directory name and the file name when you use it.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by