Error in mergint .txt files

1 回表示 (過去 30 日間)
Ivan Mich
Ivan Mich 2020 年 11 月 29 日
コメント済み: Ameer Hamza 2020 年 11 月 29 日
I am using this code in order to merge vertically .txt files. Command error shows me that:
Error using fscanf
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in test_V2 (line 51)
data = fscanf(fid_t,'%c');%read data
My code is:
fid_p = fopen('FINale.txt','w'); % writing file id
x= dir ('Fin*.txt');
for i =1:length(x)
filename = ['Fin',num2str(i),'.txt'];%filename
fid_t=fopen(filename,'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
Could you help me please?

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 11 月 29 日
You are probably creating the filename incorrectly in the line
filename = ['Fin',num2str(i),'.txt'];%filename
Try the following code
fid_p = fopen('FINale.txt','w'); % writing file id
x = dir('Fin*.txt');
for i =1:length(x)
filename = fullfile(x(i).folder, x(i).name);%filename
data = fileread(filename);%read data
fprintf(fid_p,'%s\n', data);%print data in File_all
end
fclose(fid_p); %close writing file id
  2 件のコメント
Ivan Mich
Ivan Mich 2020 年 11 月 29 日
Thank you. I have tried your code and it works. But there is a problem. Between each line there is an empty line without data. I would like to "remove" this line. How could I make it?
Ameer Hamza
Ameer Hamza 2020 年 11 月 29 日
Try writing without the newline character at the end. For example, change the fprintf() call to
fprintf(fid_p,'%s', data);%print data in File_all

サインインしてコメントする。

その他の回答 (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