Write in a file, one ligne before the last one
Show older comments
Hi
So i have a function file, and i want to write inside the file. ( sounds weired i know)
but i want toto write one ligne before the last line in the function script.
i made up this eexemole to explaine :
function [out_1, out_2] = test (in_1, )in_2
stuf ... % thethe main code of the function
end
i am using this code toto write inside the function file
file = fopen('test.m','a+')
fprintf(file,'%c','stuf')
fclose(file)
the idea is i want to write before the "end" of the function.
is there a way to Go back 3 caracters or up one ligne to sstart writing?
Accepted Answer
More Answers (1)
Mario Malic
on 1 Sep 2020
Edited: Mario Malic
on 1 Sep 2020
With this, you'll get contents of the file in File_Data which is a cell size (ii,1) with character arrays.
FID = fopen('test.txt', 'r');
ii = 1;
tline = fgetl(FID);
File_Data{ii} = tline;
while ischar(tline)
ii = ii+1;
tline = fgetl(FID);
File_Data{ii} = tline;
end
fclose(FID);
Replacing the second to last line
File_Data{numel(File_Data)-1} = 'Henry the IXth I am';
You can delete the previous file, I am not sure if fopen would overwrite the file if it has the same name.
Write the file with
FID = fopen('test1.txt','wt'); %
for p = 1:numel(File_Data)
if File_Data{p+1} == -1 % -1 denotes the end of file
fprintf(FID,'%s', File_Data{p});
break
else
fprintf(FID,'%s\n', File_Data{p});
end
end
fclose(FID);
4 Comments
Khalala Mamouri
on 1 Sep 2020
Mario Malic
on 1 Sep 2020
Command movefile as the name says will move (rename or copy) your file.
Khalala Mamouri
on 1 Sep 2020
Mario Malic
on 1 Sep 2020
You changed the order of files
From the documentation:
movefile source destination
%
movefile 'old.txt' 'new.txt'
Categories
Find more on Low-Level File I/O in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!