Writing a text file with information from a data file

1 次查看(过去 30 天)
Hi, I need to be able to take a .dat file that contains 5 strings of the filenames of .jpg images, and out put a .txt file that contains the name of each string and other data for EACH string (i.e. each .jpg image). I figured out how to generate this for one of the strings, but I don't know how to do it for all of the strings. Maybe use some sort of loop?
fileID = fopen('nameOfFile.dat');
filename = fgets(fileID)
fileID2 = fopen('nameOfFile.txt','wt');
info = 'blah blah';
num = 5;
fprintf(fileID2,'Filename: %s\n Info: %s\n Number: %g\n',filename,info,num);
fclose(fileID);
fclose(fid);
--------------------------------------------------------------------------------
UPDATE: I have figured out how to generate this for all of the strings, but I can only do it if I know how many strings there are. I need to be able to do it with any input data file (not just one with 5 strings). Also, I need the info and num to be able to be different for each filename.
fileID = fopen('nameOfFile.txt','wt');
filename = textread('nameOfFile.dat','%s\n')
info = 'blah blah blah';
num = 5;
fprintf(fileID,'Filename: %s\nInfo: %s\nNumber: %g\n',filename{1},info,num,filename{2},info,num,filename{3},info,num,filename{4},info,num,filename{5},info,num);
fclose(fileID);
  1 个评论
Jonathan
Jonathan 2012-6-25
I figured it out! It was much simpler than I thought.
fileID = fopen('nameOfFile.txt','wt');
filename = textread('nameOfFile.dat','%s\n');
for i = 1:length(filename)
info = 'blah blah blah';
num(i) = 5;
fprintf(fileID,'Filename: %s\nInfo: %s\nNumber: %g\n\n',filename{i},info,num(i));
end
fclose(fileID);

请先登录,再进行评论。

采纳的回答

per isakson
per isakson 2012-6-25
This is a hint!
% or a more specific wildcard pattern
sad = dir( fullfile( folder_spec, '*.dat' ) );
file_name_list = permute( { sad.name }, [2,1] ); % row vector
fileID = fopen('nameOfFile.txt','wt');
for file_name = file_name_list % loop over all files
image_file_name = textread( fullfile(folder_spec,file_name{:}, ... );
info = something
num = something else
fprintf( fileID, 'Filename: %s\nInfo: %s\nNumber: %g\n' ...
, image_file_name, info, num )
end
fclose( fileID );

更多回答(0 个)

类别

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