copy the content of a text file to another text file
조회 수: 26 (최근 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!