Find files of a certain extension and populate a structure field with those file names.

17 ビュー (過去 30 日間)
I have a directory with multiple .txt files. I want find all those .txt files and create a structure field with the names of those files. I've tried the following:
>> dir(strcat(pwd,'\','*.txt'))
Test_1.txt Test_2.txt Test_3.txt
>> struct1.file_names = dir(strcat(pwd,'\','*.txt'))
struct1 =
struct with fields:
file_names: [3×1 struct]
>> struct1.file_names
ans =
3×1 struct array with fields:
name
folder
date
bytes
isdir
datenum
I don't understand why these three commands:
dir(strcat(pwd,'\','*.txt'))
struct1.file_names = dir(strcat(pwd,'\','*.txt'))
struct1.file_names
produce different outputs. I also don't know how to populate struct1.file_names with the names of my .txt files. Can someone please help?

採用された回答

Scott MacKenzie
Scott MacKenzie 2022 年 3 月 18 日
編集済み: Scott MacKenzie 2022 年 3 月 18 日
Your second command is wrong. The dir command returns a structure. You don't need to append ".file_names". The filenames are part of the structure returned by dir. Try this:
struct1 = dir(strcat(pwd,'\','*.txt')) % show the structure returned by dir
struct1.name % show the filenames within the structure returned by dir
  2 件のコメント
Allen Hammack
Allen Hammack 2022 年 3 月 18 日
Thank you! Using your suggestion, I was able to get what I need.
I ended up using part of the solution provided by "-" below.
Scott MacKenzie
Scott MacKenzie 2022 年 3 月 18 日
@Allen Hammack, you're welcome. Good luck.

サインインしてコメントする。

その他の回答 (1 件)

Voss
Voss 2022 年 3 月 18 日
dir() with no output argument (i.e., not assigning the result to any variable) displays the result to the command line.
S = dir() with an output argument (i.e., assigning to the variable S in this case) gives you an array of structs, each element of which corresponds to one item (that is, one file or folder) and contains the file (or folder) name as well as other information.
Assigning the output of your dir() call (rewritten here to use fullfile()) to a variable seems like it will give you the information you want
struct1 = dir(fullfile(pwd(),'*.txt'))
struct1 = 0×1 empty struct array with fields: name folder date bytes isdir datenum
names = {struct1.name}
names = 0×0 empty cell array
struct1 = dir() % get everything, not just .txt files
struct1 = 2×1 struct array with fields:
name folder date bytes isdir datenum
names = {struct1.name}
names = 1×2 cell array
{'.'} {'..'}
  2 件のコメント
Allen Hammack
Allen Hammack 2022 年 3 月 18 日
Thank you! Your solution was helpful! I ended up using part of it to get what I needed. I mainly used the solution that was submitted before yours, so I accepted that one. Thanks!
Voss
Voss 2022 年 3 月 18 日
You're welcome!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by