uigetfile saving script name as selected file

6 views (last 30 days)
New to matlab and I'm sure there is a simple solution,
This is my code
file=uigetfile('Select the file');
fid=fopen(file);
text=fileread(file);
disp(text);
I'm just trying to open a text file and parse it , pulling out certain variables (without altering the file )
However, when It promptsthe user for the file it then saves my script to the file name that the user selected
Thanks
  1 Comment
Geoff Hayes
Geoff Hayes on 30 Aug 2019
Charlotte - please clarify what you mean by it then saves my script to the file name that the user selected. Which script? The script that contains the above code? Are you saying that file becomes the name of your script?

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 30 Aug 2019
You don't need fopen(). Try this:
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = pwd; % or 'C:\wherever';
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)
fileContensts = fileread(fullFileName);
Do NOT use text as the name of your variable since that is the name of an important built-in function.
Here's another alternative where it's read in line-by-line
% Open the file.
fileID = fopen(fullFileName, 'rt');
% Read the first line of the file.
textLine = fgetl(fileID);
while ischar(textLine)
% Print out what line we're operating on.
fprintf('%s\n', textLine);
% Read the next line.
textLine = fgetl(fileID);
end
% All done reading all lines, so close the file.
fclose(fileID);

Categories

Find more on App Building in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!