Problem with fscanf command in creating .txt file
5 次查看(过去 30 天)
显示 更早的评论
I would like to create an output .txt file. This .txt file is a result of merging vertically multiple .txt files with the same suffix.
I have this script but I have problem with fscanf.
fid_p = fopen('final.txt','w'); % writing file id
x= dir ('*new.txt');
for i =1:length(x)
filename1 = ['*new.txt'];%filename
fid_t=fopen(filename1,'r');%open it and pass id to fscanf (reading file id)
data = fscanf(fid_t,'%c');%read data
fprintf(fid_p,'%c',data);%print data in File_all
fclose(fid_t);% close reading file id
fprintf(fid_p,'\n');%add newline
end
fclose(fid_p); %close writing file id
I am importing one example of my files (Imagine that all my files have 3 columns, and the first include strings/characters)
Could you please help me?
2 个评论
Jan
2021-3-2
"I have this script but I have problem with fscanf." - If you mention, what the problem is, we can suggest an improvement.
采纳的回答
Jan
2021-3-2
编辑:Jan
2021-3-2
filename1 = ['*new.txt'];%filename
fid_t=fopen(filename1,'r')
This cannot work: '*new.txt' is not a valid file name, because the * is not allowed.
fid_p = fopen('final.txt','w'); % writing file id
if fid_p < 0, error('Cannot open file for writing.'); end
x = dir ('*new.txt');
for i = 1:length(x)
filename1 = x(i).name; %filename
fid_t = fopen(filename1, 'r');%open it and pass id to fscanf (reading file id)
if fid_t < 0, error('Cannot open file for reading.'); end
data = fread(fid_t, inf, '*char');%read data
fwrite(fid_p, data, 'char');%print data in File_all
fclose(fid_t);% close reading file id
fprintf(fid_p,'\n');%add newline
end
fclose(fid_p); %close writing file id
This take the file name from the list of files in x. In addition it uses FREAD and FRWITE, because it is faster to access the files in binary mode.
Never use FOPEN without testing the success.
Working with relative paths is less reliable than absolute path names:
Folder = 'C:\Your\Folder';
FileList = dir (fullfile(Folder, '*new.txt'));
for iFile = 1:numel(FileList)
FileName = fullfile(Folder, FileList(iFile).name);
...
end
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!