Reputation: 1035
I have several files in .txt format. My goal is to unify the content of all these files into a source file (also .txt format) without changing the formatting. To start, I just want to copy the content from one file to another.
The following code snip allows to copy the content. However, I lose the formatting.
% load destination file in append mode
destFileId = fopen(destFile, "a");
% load source file in read mode
sourceFileId = fopen(sourceFile, "r");
% Extract content from source file
content = textscan(sourceFileId, '%c');
% Append content into destination file
fprintf(destFileId, content{:});
% Close both files
fclose(destFileId);
fclose(sourceFileId);
Upvotes: 0
Views: 304
Reputation: 22304
The problem with using fprintf
to concatenate files is that if the file contains special characters (like \
or %
) then fprintf
will likely fail. A very similar approach would be to use fread
and fwrite
to directly concatenate the file contents without interpreting them in any way.
function catfiles(dest, sources)
fdest = fopen(dest, 'wb');
for source = 1:numel(sources)
fsource = fopen(source,'rb');
source_data = fread(fsource);
fwrite(fdest, source_data);
fclose(fsource);
end
fclose(fdest);
Usage
>> catfiles('dest.txt', {'source1.txt', 'source2.txt'});
I didn't include all the checks that @CitizenInsane's answer does but they are a good idea.
Upvotes: 1
Reputation: 4875
I think using fileread
instead of textscan
will help in preserving formattiing as you wish to (fileread
reads whole file content as a simple matlab string, preserving both for whitespaces and newlines)
Here is some pseudo code (not tested):
function [] = Dummy(desFile, sourcesFiles)
%[
% Open destination file for writing (discarding previous content)
[destFileId, msg] = fopen(destFile, 'w');
if (desFileId < 0), error(msg); end
% Make sure to close file on any error, ctrl+c (and normal termination of course)
cuo = onCleanup(@()fclose(destFileId));
% Copy file contents to destination
count = length(sourcesFiles);
for fi = 1:count,
text = fileread(sourcesFiles{fi});
fprintf(destFileId, '%s', text);
end
%]
Upvotes: 4