MATLAB: Error in .exe but not in .m file

.exe problemMATLAB Compiler

Here is my program, reading a folder(let's say five .txt file in this folder)and the information where in the txt file will display on the Textbox,my program works well in .m file, but once I convert to .exe file, the error occurred on reading function (fid = -1, 'Invalid file identifier'), so I had to check this problem, and I found that if I didn't 'add path' my test folder to the working environment, the same problem occurred again…below shows the code of the reading function:
if true
% code
==================================================
inputData = dir(fullfile(inputPath,'*.txt'));
fileLength = length(inputData);
for i = 1:fileLength
fileName = inputData(i).name;
fid = fopen(fileName, 'rt');
%%%%%%%%%%%%test %%%%%%%%%%%%%%
display(num2str(fid));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end

Best Answer

Use an absolute path:
inputData = dir(fullfile(inputPath,'*.txt'));
fileLength = length(inputData);
for i = 1:fileLength
fileName = inputData(i).name;
file = fullfile(inputPath, fileName); % Absolute path
fid = fopen(file, 'rt');
if fid == -1, error('Cannot open file: %s', file); end