How do I fix this code to copy text from a number of text files to a bunch of other text files?

4 views (last 30 days)
I have a number of text files in a directory. I want to copy the contents of each of these text files into brand new text files except I do not want to copy the first 4 lines. For this I have written this code but it is not working. Can you help me fix this?
files = dir('*.TXT')
N = numel(files)
count = 0;
for i = 1:N
fid1 = files(i).name
disp(fid1)
a = fopen(fid1,'r')
file_name = [sprintf('%1.0f',i) '.txt'];
fopen(file_name,'w+');
for K = 1:4
inline = fgetl(a)
end
while ischar(inline)
inline = fgetl(a)
fprintf(file_name,'%s\n\r',inline)
end
fclose('all')
end

Accepted Answer

dpb
dpb on 4 Aug 2017
for i = 1:length(files)
disp(fid1)
fidI = fopen(files(i).name,'r');
file_name = [sprintf('%1.0f',i) '.txt']; % would recommend use a more descriptive name
fidO=fopen(file_name,'w+'); % you didn't save the file handle...
for K = 1:4, inline=fgetl(a); end % skip the four records
while ischar(inline)
inline = fgets(a); % get line, include \n
fprintf(fidO,'%s',inline) % write output; \n is in string by dint of fgets
end
fclose('all')
end

More Answers (0)

Categories

Find more on File Operations 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!