Overwriting specific line in a text file and data export

3 次查看(过去 30 天)
Hello,
I'm having trouble trying to export the data from my code into the following format, 'FLUX FACTORS.txt.' Its easy enough to just export the data as a text file, but the problem is is that the program I plan to use this file as an input for requires that I keep the same formatting as 'FLUX FACTORS.txt' (it was based on punch cards).
How do I export the data in my code variable FLUX and have it follow the same configuration as 'FLUX FACTORS.txt.'
Secondly, how can I overwrite a single line from 'HISTORY.txt' (specifically line 3) and overwrite it with my data from 'FLUX FACTORS.txt.' e.g. for one run, I'd like to replace line 3 in 'History.txt' with line 5 from 'FLUX FACTORS.txt.'
I have attached my code and the input files below.
Thanks in advance,
Quang

采纳的回答

KSSV
KSSV 2019-2-4
file1 = 'FLUX FACTORS.txt' ;
file2 = 'HISTORY.txt' ;
% REad file1
fid = fopen(file1,'r') ;
S1 = textscan(fid,'%s','delimiter','\n') ;
S1 = S1{1} ;
fclose(fid) ;
% REad file2
fid = fopen(file2,'r') ;
S2 = textscan(fid,'%s','delimiter','\n') ;
S2 = S2{1} ;
fclose(fid) ;
% Replace 3rd line of file2 with 5th lines of file1
S2{3} = S1{5} ;
% Write the edited to file
fid = fopen('data.txt','wt') ;
fprintf(fid,'%s\n',S2{:});
fclose(fid);
  1 个评论
Quang Phung
Quang Phung 2019-2-4
编辑:Quang Phung 2019-2-4
Thanks for the assistance, the code works, but I am encountering an issue with using the text file as an input. While the code is able to overwrite the specific line in question it also deletes the initial spaces in the text file.
Unfortunately, I need that space (the exe is VERY specific) at the beginning. Is there a way for me to keep that initial space at the beginning.
I've attached a screenshot showing what I mean. The top image is a valid input HISTORY.txt file, and the bottom is a MATLAB exported version. I need to follow that spacing configuration exactly.
Thanks,
Quang
Edit:
I've also included a valid and not valid history file. The main difference is simply that initial spacing.

请先登录,再进行评论。

更多回答(0 个)

类别

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

标签

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by