I get error, 'Error using fopen File identifier must be an integer-valued scalar of type double.'

5 Ansichten (letzte 30 Tage)
This are my two first lines of code,
[filename, path] = uigetfile ('*.txt','Select input file name');
fid = fopen ([path, filename], 'r');
Those anyone know what might be causing this error to show up?

Antworten (1)

Shivam
Shivam am 1 Sep. 2024
Hi Luis,
From the information provided, I understand that you are encountering an error while using the uigetfile and fopen MATLAB functions.
The uigetfile basically opens a modal dialog box let you choose the specified file type (here, .txt). The error you are encountring is because the opened dialog box is being closed without selecting the file. Due to which, uigetfile returns 0 for both 'filename' and 'path'. This further causes fopen to open a non-existing file leading to the error mentioned.
You can follow the below workaround to handle the error scenario:
[filename, path] = uigetfile('*.txt', 'Select input file name');
% Check if the user canceled the file selection
if isequal(filename, 0) || isequal(path, 0)
error('File selection canceled.');
else
% Construct the full file path
fullFilePath = fullfile(path, filename);
% Open the file
fid = fopen(fullFilePath, 'r');
% Check if the file was opened successfully
if fid == -1
error('Failed to open file: %s', fullFilePath);
else
%
% Do the operations with the opened file
%
fclose(fid); % close the file when done
end
end
You can visit these documentations links as well to understand more about 'uigetfile' and 'fopen' function:
I hope it helps in resolving the issue.

Kategorien

Mehr zu Programming Utilities finden Sie in Help Center und File Exchange

Produkte


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by