copy the content of a text file to another text file
33 views (last 30 days)
Show older comments
Hello,
I have several text files and each contains 3 things that I need to know(user name, date, comments). I am interested to create another text file where I want to copy only the comment from each file. (So to see a history of all the comments.)
I tried this:
fid = fopen('info.txt'); //my txt file containing the 3 info
F = fread(fid, '*char')'
fclose(fid);
CommentsHistory = fopen('CommentsHistory.txt', 'wt');
fprintf(CommentsHistory,'\nComments history:\n\n');
fprintf(CommentsHistory,'%-50s\t',F);
fclose(CommentsHistory);
But with no result, I can see only the result of this line:
fprintf(CommentsHistory,'\nComments history:\n\n');
I must say that I tried with this code to copy everything what is in info.txt (so not only the comments). Copying only the comments probably will be another problem...
1 Comment
Jan
on 14 Dec 2011
Does your F contain any zeros? can you display it in the command window? Are you looking to the correct folder?
Answers (2)
Eric Pahlke
on 15 Dec 2011
Not sure why why your code doesn't work, did you try:
open CommentsHistory.txt
The code below is how I solved a similar problem of trying to get data from specific fields in a text file. It only works if the relevant strings are on the same line as a unique text cue (stored in the first column of "Fields") that indicates where they sit in the file.
fid = fopen('info.txt'); %my txt file containing info
% First column is the identifier to searched for
% Second column is the var name to store the data in
Fields = {
'UserName: ', 'UN';...
'Date: ' , 'D';...
'Comments: ', 'Com';...
};
for jj = 1:length(Fields)
found = 0;
frewind(fid); % With this the fields can be out of order
% Advance the file until we find the text cue,
% then save the value
while ~found
currentline = fgetl(fid);
if currentline == -1
% End of file
error('Text cue not found: %s',Fields{jj,1});
end
startind = strfind(currentline,Fields{jj,1});
if ~isempty(startind)
% Dont want to count the identifier as data
startind = startind + length(Fields{jj,1});
val = currentline(startind:end);
% The next line stores the data in the variable
% named in column 2 of "Fields"
eval(sprintf('%s = val;',Fields{jj,2}));
found = 1;
end
end
end
fclose(fid);
fid2 = fopen('CommentsHistory.txt', 'w');
fprintf(fid2,'\nComments history:\n\n');
fprintf(fid2,'%s',Com);
fclose(fid2);
fprintf(' Name was %s, Date was %s, Comments was %s',UN,D,Com)
The example info.txt I checked this with is:
UserName: Bob
Date: 2/22/2002
Comments: These are my comments
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!