Copyfile without overwriting

Hello!
How can I copy the content of a *.m file in another. I used copyfile('1.m','2.m') but with this command the content of 2.m will be overwriten by the content of 1.m.
Ex: 1.m content: test1; 2.m content: test 2. I am expecting to get after using copyfile the content of 2.m like: test 2, test1.
I also used the next lines but it is not looking ok.. % fid = fopen('first.m'); % F= fread(fid, '*char')'; % fclose(fid);
Thanks!

 채택된 답변

Honglei Chen
Honglei Chen 2012년 2월 28일

0 개 추천

I don't think you can do that with copyfile. You can do it with fopen, but you need to open it with option 'a', and then append the content you want.
doc fopen
Here is an example
fid1 = fopen('1.m','r');
fid2 = fopen('2.m','a');
while 1
tline = fgetl(fid1);
if ~ischar(tline), break, end
fprintf(fid2,'%s\n',tline);
end
fclose(fid1);
fclose(fid2);

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2012년 2월 28일

0 개 추천

You could use fwrite, or fprintf to write to the end of the file, fgetl would also be your friend.

댓글 수: 6

Diana Acreala
Diana Acreala 2012년 2월 28일
In sure that 'fgetl' helps me..but I don't understand how it works..
Honglei Chen
Honglei Chen 2012년 2월 28일
To use all of these you need to use fopen first to open the file. You can open your 1.m in 'r' mode and 2.m in 'a' mode. You can then get each line from 1.m using fgetl and write them to 2.m using fwrite or fprintf.
Diana Acreala
Diana Acreala 2012년 2월 28일
%script
FileDir = mfilename('fullpath');
all_files=what;
only_m_files=all_files.m;
%type the name of the needed file
filename = input('Enter name of file: ', 's');
for k=1:length(only_m_files)
if strcmp(only_m_files{k,1},'script.m')==1
elseif strcmp(only_m_files{k,1},filename)==1
else
fid = fopen(only_m_files{k,1});
F{k,1}= fread(fid, '*char')';
fclose(fid);
end
end
% Create the file
fid = fopen(filename, 'w');
for k=1:length(F)
fwrite(fid, F{k,1});
end
fclose(fid);
Diana Acreala
Diana Acreala 2012년 2월 28일
With this looks that is working, but.. the problem is with the 'fgetl' command.. where in this code shoul I use it?
Honglei Chen
Honglei Chen 2012년 2월 28일
I added an example in my answer above
Diana Acreala
Diana Acreala 2012년 2월 28일
Great! I adapted with your example and it's working! Thanks a lot!

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

카테고리

Community Treasure Hunt

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

Start Hunting!

Translated by