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 Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by