Problem with fscanf command in creating .txt file

3 次查看(过去 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
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.
Ivan Mich
Ivan Mich 2021-3-2
command window shows me:
Error using fscanf
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in code (line 32)
data = fscanf(fid_t,'%c');%read data

请先登录,再进行评论。

采纳的回答

Jan
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 个)

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by