필터 지우기
필터 지우기

How can I edit a '.m' file by another '.m' file ?

조회 수: 44 (최근 30일)
Abhijit Chougule
Abhijit Chougule 2017년 2월 18일
댓글: BABANBHAIGARI SHAFIULLAH 2021년 8월 31일
Can we edit a '.m' file from another '.m' file ? Like we can modify/update a model and save it by a M script.

채택된 답변

Image Analyst
Image Analyst 2017년 2월 18일
Yes. Open it with fopen(), get lines out into strings with fgetl(), modify them as needed. Open an output file with fopen(), write the modified lines out. Close both files with fclose(). Delete the input file with delete(). Rename the output file to the input filename with movefile().
  댓글 수: 7
Image Analyst
Image Analyst 2021년 8월 31일
@BABANBHAIGARI SHAFIULLAH, open a file for reading and writing. Then read until you recognize the section, then write to the output file:
% Open the input file for reading in text mode.
inputFileID = fopen(inputFullFileName, 'rt');
% Open the output file for appending in text mode.
outputFileID = fopen(outputFullFileName, 'at');
% Read the first line of the file.
textLine = fgetl(inputFileID);
lineCounter = 1;
writeToOutput = false; % Set to true once we get to the section we want.
while ischar(textLine)
% Print out what line we're operating on to the command window.
fprintf('%s\n', textLine);
% Read the next line.
textLine = fgetl(inputFileID);
lineCounter = lineCounter + 1;
if contains(textLine, '%%% Acceleration %%%')
writeToOutput = true;
end
if writeToOutput
fprintf(outputFileID, '%s\n', textLine);
end
end
% All done reading all lines, so close the files.
fclose(inputFileID);
fclose(outputFileID);
BABANBHAIGARI SHAFIULLAH
BABANBHAIGARI SHAFIULLAH 2021년 8월 31일
It worked for me. Thank you @Image Analyst for the detailed explanation.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by