Problem with fscanf command in creating .txt file

조회 수: 2 (최근 30일)
Ivan Mich
Ivan Mich 2021년 3월 2일
편집: Jan 2021년 3월 2일
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