Help naming text file according to user input

Asked by David about 13 hours ago
Latest activity Commented on by David about 12 hours ago

Hello everyone,

I am trying to create a text file (using a gui), and I would like the name of the file to match what the user inputs in an edit text box. At first, I am trying to use a simple script (attached below) to see if I can accomplish this, but I am unable to create the .txt file. The file being created is just a "file". What would be the best way to approach this? Am I on the right track?

Thank you in advance for any help provided.

Code:
prompt = 'Please enter the file name: ';
fileName = input(prompt,'s');
% open a file for writing
fid = fopen(fileName, 'wt');
if fid == -1
  error('Cannot open file: %s', fileName);
end

0 Comments

David

Products

No products are associated with this question.

1 Answer

Answer by Ahmed A. Selman about 12 hours ago
Accepted answer

Just add the extension you like to the variable (fileName), as

 prompt = 'Please enter the file name: ';
 fileName = input(prompt,'s');
 fileName1=[fileName,'.txt']; % HERE. Choose different extension if you like.
 % open a file for writing
 fid = fopen(fileName1, 'wt'); % HERE
 if fid == -1
   error('Cannot open file: %s', fileName1); AND HERE
 end
  % (HERE indicates changes I've made)

:-)

1 Comment

David about 12 hours ago

Thank you for the rapid response. When I was trying to add the extension, I was doing it all in one line and I kept getting errors. It makes sense to append it separately. Thank you so much!

Ahmed A. Selman

Contact us