copy the content of a text file to another text file
30 次查看(过去 30 天)
显示 更早的评论
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 个评论
Jan
2011-12-14
Does your F contain any zeros? can you display it in the command window? Are you looking to the correct folder?
回答(2 个)
Eric Pahlke
2011-12-15
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Live Scripts and Functions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!