How to store a data of a structure into a text file.

1 次查看(过去 30 天)
I have created a structure in which 4 variables are defined. How to store the values of structure into a text file.

采纳的回答

Geoff Hayes
Geoff Hayes 2015-1-13
Priyanka - if you just want to write the structure to file, then just try using fopen to open the file, fprintf to write the data (each of the four variables) to file, and fclose to close the file.

更多回答(1 个)

samesu naq
samesu naq 2018-12-10
s1.name = 'fred';
s1.age = 42;
s1.height = 170;
s1(2).name = 'alice';
s1(2).age = 29;
s1(2).height = 160;
fileID = fopen('use of structure .txt','a');
fprintf(fileID, 'Missile # :%s \n', s1.name);
fprintf(fileID, 'Operator Name :%s \n', s1.age);
fprintf(fileID, 'Operator Name :%s \n', s1.height);
fprintf(fileID, 'Missile Type :%s \n', s1(2).name);
fprintf(fileID, 'Missile ID :%s \n',s1(2).age);
fprintf(fileID, 'Container Number :%s \n', s1(2).height);
fclose(fileID);
simply fprintf is not write structure variable in text file
Error occur ''Scalar structure required for this assignment.
Error in Untitled (line 36)
s1.name = 'fred';''
  1 个评论
Walter Roberson
Walter Roberson 2021-6-11
编辑:Walter Roberson 2021-6-11
s1(1).name = 'fred';
s1(1).age = 42;
s1(1).height = 170;
s1(2).name = 'alice';
s1(2).age = 29;
s1(2).height = 160;
fileID = fopen('use of structure .txt','a');
fprintf(fileID, 'Missile # :%s \n', s1(1).name);
fprintf(fileID, 'Operator Name :%s \n', s1(1).age);
fprintf(fileID, 'Operator Name :%s \n', s1(1).height);
fprintf(fileID, 'Missile Type :%s \n', s1(2).name);
fprintf(fileID, 'Missile ID :%s \n', s1(2).age);
fprintf(fileID, 'Container Number :%s \n', s1(2).height);
fclose(fileID);

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Low-Level File I/O 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by