- Reading 4th line and creating the changed version based on userInput1 and userInput2.
- Writing all the lines in a new file with changed 4th line.
Changing values(parameteres) in input text file at a certain line
1 次查看(过去 30 天)
显示 更早的评论
MATErial,1
SOLId
PLANe STRAin
ELAStic ISOTropic 1000.0 0.25
! Blank termination record
COORdinates
1 0 0.0 0.0
2 0 4.0 0.0
3 0 10.0 0.0
4 0 0.0 4.5
5 0 5.5 5.5
6 0 10.0 5.0
7 0 0.0 10.0
8 0 4.2 10.0
9 0 10.0 10.0
! Blank termination record
ELEMents
1 1 1 1 2 5 4
2 1 1 2 3 6 5............................
The text file looks like this. I want to change the fourth line last two parameters 1000.0 and 0.25 to user defined input parameters and run the system command to execute the input text file in external program. Any help could you greatly appreciated. Thanks in advance
0 个评论
采纳的回答
Raunak Gupta
2020-3-16
Hi,
You can use textscan while reading specific line from the text file and in this case it’s the 4th line. Since there is some initial whitespaces in the 4th line which will go after reading from textscan I have added a tab character which compensates for same.
The following code may help you achieved the same.
userInput1 = 50; % User Input 1
userInput2 = 0.5; % User Input 2
% Original File
fid=fopen('check_nf.txt','r');
linenum = 4;
C = textscan(fid,'%s',1,'delimiter','\n', 'headerlines',linenum-1);
line_4_words = strsplit(string(C{1}));
line_4_words(3) = num2str(userInput1);
line_4_words(4) = num2str(userInput2);
changedLine = sprintf('\t') + join(line_4_words) + newline;
fclose(fid);
count = 1;
fid=fopen('check_nf.txt','r');
% New File
fod=fopen('new_nf.txt','w');
while ~feof(fid)
if count == 4
fprintf(fod,'%s',changedLine);
fgets(fid);
else
fprintf(fod,'%s',fgets(fid));
end
count = count + 1;
end
fclose(fod);
fclose(fid);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Export 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!