Home > Software design >  Creating a valid filename with dir and fullfile
Creating a valid filename with dir and fullfile

Time:05-18

I keep running across this error in my code:

Path = 'C:\Users\18606\OneDrive\Documents\Spheroids For Brandon\Spheroids\1-8WT';
Content = dir(Path); 
SubFold = Content([Content.isdir]); % Keep only the directories
MyData = []; 
for k = 3:length(SubFold)
    F = fullfile(Path, SubFold(k).name);
    fileID = fopen(F);
    MyData{end 1} = fopen(fileID,'%s\n');
    fclose(fileID);

Resulting in the error:

Error using fopen
Invalid filename (line 8)

The code is trying to iterate over multiple images in multiple subfolders of the main. The goal is to process the images with an edge detection algorithm for each file, but that's besides the point. Why would the program give an invalid file name when the path, content and subfolders are all specified in the code? Do the variables mentioned have anything to do with the error? Finally, is there a better way to open and read the images iteratively?

CodePudding user response:

Reading in files sequentially is indeed usually done through looping over a dir() call, i.e. your strategy is valid. What's going wrong here, is that Path is a path to a directory, not a file. SubFold then are only directories as they are found on the Path. fullfile(Path, SubFold(k).name) finally creates a path to a subdirectory of Path. A subdirectory is not a file, thus fopen will tell you that it's an incorrect filename.

You'll probably need another dir() call, e.g. dir(F) to get all files on the path specified by F.

  • Related