首页 > 解决方案 > 获取文件夹+文件名输出

问题描述

在链接中:[ https://www.mathworks.com/help/matlab/creating_guis/interactive-list-box-in-a-guide-gui.html][1]我可以在 GUIDE 中创建交互式列表框应用程序

我试图添加到行尾, function listbox1_Callback(hObject, eventdata, handles)所以 fullFileName = [path,name,ext] 我可以获得路径、名称和扩展名的输出(例如,F:/user/mySoft.m),但它不起作用。我该怎么做?

function listbox1_Callback(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns listbox1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox1

get(handles.figure1,'SelectionType');
if strcmp(get(handles.figure1,'SelectionType'),'open')
    index_selected = get(handles.listbox1,'Value');
    file_list = get(handles.listbox1,'String');
    filename = file_list{index_selected}
    [path,name,ext] = fileparts(filename)
    fullFileName = [path, name, ext]
end

% ------------------------------------------------------------
% Read the current directory and sort the names
% ------------------------------------------------------------
function load_listbox(dir_path,handles)
cd (dir_path)
dir_struct = dir(dir_path);
[sorted_names,sorted_index] = sortrows({dir_struct.name}');
handles.file_names = sorted_names;
handles.is_dir = [dir_struct.isdir];
handles.sorted_index = sorted_index;
guidata(handles.figure1,handles)
set(handles.listbox1,'String',handles.file_names,...
    'Value',1)
set(handles.text1,'String',pwd)

  [1]: https://www.mathworks.com/help/matlab/creating_guis/interactive-list-box-in-a-guide-gui.html

标签: matlab

解决方案


要构造完整的文件地址,您可以使用 fullfile 函数。

fullfile(path1,path2,...,filename)

但我认为你想这样做

which(filename)

当您使用变量filename调用文件时,which命令将为您提供文件的完整地址。

示例代码:

filename="mySoft.m"; %this file does not exist in my computer
address=which(filename);
filename="dosyaBul.m"; %this does exist
address=which(filename)

输出:

address =

  0×0 empty char array


address =

    'C:\Users\volk\Dropbox\folder\Matlab\dosyaBul.m'

请注意,您还可以使用 pwd 在 Matlab 上获取活动文件夹。就我而言:

>>pwd

ans =

'C:\Users\volk\Dropbox\folder\Matlab'

推荐阅读