MATLAB: Problem with processing files in a for loop

for looptext file

My problem is that when I use the script below, it works, but when I put it into loop, it crashes. Why is it so?
names = dir('C:\Users\User\Documents\OZEApp\tests\BufforTest*.txt');
names = {names.name};
fileName = names{4};
path = strcat('C:\Users\User\Documents\OZEApp\tests\', fileName);
pathMatlab = strcat('C:\Users\User\Documents\OZEApp\testMatlab\', fileName);
charPath = convertStringsToChars(path);
charPathMatlab = convertStringsToChars(pathMatlab);
Data = fileread(charPath);
Data = strrep(Data, ',', '.');
New = fopen(charPathMatlab, 'w');
fwrite(New, Data, 'char');
fclose(New);
fid=fopen(charPathMatlab);
This one doesn't work:
names = dir('C:\Users\User\Documents\OZEApp\tests\BufforTest*.txt');
names = {names.name};
for fileName = names'
path = strcat('C:\Users\User\Documents\OZEApp\tests\', fileName);
pathMatlab = strcat('C:\Users\User\Documents\OZEApp\testMatlab\', fileName);
charPath = convertStringsToChars(path);
charPathMatlab = convertStringsToChars(pathMatlab);
Data = fileread(charPath);
Data = strrep(Data, ',', '.');
New = fopen(charPathMatlab, 'w');
fwrite(New, Data, 'char');
fclose(New);
fid=fopen(charPathMatlab);
end

Best Answer

Don't say what doesn't work or give error message, but the first dereferences a single element of the directory structure while the last simply provides the cell content. Many (most) of the file handling routines haven't been updated to use cellstr so guessing that would be where the problem lies...
Can write a little more simply if just use straight-ahead constructs instead of trying to get fancy--
d=dir('C:\Users\User\Documents\OZEApp\tests\BufforTest*.txt');
for i=1:length(d)
path = fullfile('C:\Users\User\Documents\OZEApp\tests', d(i).name);
pathMatlab = fullfile('C:\Users\User\Documents\OZEApp\testMatlab\', d(i).name);
Data = fileread(charPath);
Data = strrep(Data, ',', '.');
New = fopen(PathMatlab, 'w');
fwrite(New, Data, 'char');
fclose(New);
end
You had an fopen call inside the loop which would also cause issues of opening each file in turn but overwrite the same file handle as were using a single variable fid