replacing the content of a text file

3 ビュー (過去 30 日間)
H R
H R 2018 年 8 月 16 日
回答済み: Image Analyst 2018 年 8 月 17 日
Hi all. I have a text file "A.txt". I have a string S='Hello World'.
How to delete from line 10 to the end of file in "A.txt" and replace those deleted contents by string S, and save the new file to "B.txt"?
  2 件のコメント
Paolo
Paolo 2018 年 8 月 16 日
What's your OS? Can you show contents of "A.txt" ?
H R
H R 2018 年 8 月 16 日
Windows 10. Please see the attached.

サインインしてコメントする。

回答 (1 件)

Image Analyst
Image Analyst 2018 年 8 月 17 日
Try this:
S='Hello World';
% Open the input file for reading.
fullInputFileName = 'A.txt';
inputFileID = fopen(fullInputFileName, 'rt');
% Open the input file for reading.
fullOuputFileName = 'B.txt';
outputFileID = fopen(fullOuputFileName, 'wt');
% Transfer the first 9 lines.
for k = 1 : 9
% Read the line.
textLine = fgetl(inputFileID);
fprintf('Transferring line #%d: "%s"\n', k, textLine);
% Write the line.
textLine = fprintf(outputFileID, '%s\n', textLine);
end
% Write S to B.txt
textLine = fprintf(outputFileID, '%s\n', S);
% All done reading all lines, so close the file.
fclose(inputFileID);
fclose(outputFileID);
fprintf('\n--------------------------------\nHere is B.txt:\n');
type(fullOuputFileName);

カテゴリ

Help Center および File ExchangeText Data Preparation についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by