How to export data based on pop-up-menu choice to a .txt file?

2 views (last 30 days)
I need to store a numerical value inside a .txt file. The value is determined based on which option in the pop-up-menu has been selected? The problem I'm having is that whenever I check the .txt file afterwards it is blank? If I remove the semi-colons then it displays the correct value for each choice, e.g. removing the semi-colon from the line a = -10; causes a = -10 to be displayed in the command window when I select the second option in the pop-up-menu? So why can't it write it onto a a text file? I've shown my code below
% --- Executes on selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu2 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu2
contents = get(hObject,'Value');
switch contents
case 1 %Nothing selected
a = 0;
fid = fopen('Cstern.txt', 'wb');
fprintf(fid, '%s\n', a);
fclose(fid);
case 2 %V-shaped sections
a = -10;
fid = fopen('Cstern.txt', 'wb');
fprintf(fid, '%s\n', a);
fclose(fid);
case 3 %U-shaped sections
a = 10;
fid = fopen('Cstern.txt', 'wb');
fprintf(fid, '%s\n', a);
fclose(fid);
case 4 %None of the above
a = 0 ;
fid = fopen('Cstern.txt', 'wb');
fprintf(fid, '%s\n', a);
fclose(fid);
end

Answers (1)

Walter Roberson
Walter Roberson on 28 Feb 2016
Perhaps it is writing to a Cstern.txt in a directory other than the one you are looking in. It is going to write the file into whatever directory is the current directory. I suggest you display pwd() to show you which directory that is.
I further suggest you get into the habit of defining a specific output directory and using fullfile() to qualify the file names so you know exactly where the output is going to end up. For example,
outdir = handles.output_directory;
outfile = fullfile( outdir, 'Cstern.txt');
...
[fid, message] = fopen(outfile, 'wb');
if fid < 0
warndlg(sprintf('Failed to open file "%s" for writing because: %s', outfile, message));
return
end
  1 Comment
Alfie Grace
Alfie Grace on 28 Feb 2016
Hi Walter, thanks for the quick answer
It's definitely writing it in the write place, whenever an option is selected in the pop-up-menu the Cstern .txt file appears in my working directory. The problem is that when I look at it, the .txt file is blank? Do you perhaps have any more possible solutions as to what I could be doing wrong?

Sign in to comment.

Categories

Find more on Environment and Settings 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!