Overwriting specific line in a text file and data export

3 views (last 30 days)
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

Accepted Answer

KSSV
KSSV on 4 Feb 2019
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 Comment
Quang Phung
Quang Phung on 4 Feb 2019
Edited: Quang Phung on 4 Feb 2019
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.

Sign in to comment.

More Answers (0)

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!