How to assign a string with extenssion to another string to be opened?

2 views (last 30 days)
Let me see if I can explain myself: I want to open any type of .txt in my SCRIPT. For this, I demand the name of the .txt to be opened, I save it onto another known for me string, and try to open it. I am trying it with this code, but I am not able to do it:
fid = input ('Enter the name of the document with the extension: ', 's');
docu = fopen('fid');
if docu == -1
disp('File open not successful');
else
disp('File open successful');
end
mat = fscanf('docu', '%f %f', [2 inf]);
It always displays docu == -1 and some errors regarding fscanf. I am not yet an expert with Matlab so I would really apreciate some help. Thank you very much, Juan

Accepted Answer

Image Analyst
Image Analyst on 24 Oct 2014
fid is usually the name given to the File ID - a handle - not to the file NAME like you did. Here, try it this way:
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = 'C:\Program Files\MATLAB';
if ~exist(startingFolder, 'dir')
% If that folder doesn't exist, just start in the current folder.
startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
fid = fopen(fullFileName);
if fid == -1
warningMessage = sprintf('Error opening file:\n%s', fullFileName);
uiwait(warndlg(warningMessage));
return;
else
disp('File open successful');
end
theArray = fread(fid, [2 inf], 'double');
fclose(fid);

More Answers (0)

Categories

Find more on Language Fundamentals in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!