Problem with fscanf command in creating .txt file

3 Ansichten (letzte 30 Tage)
Ivan Mich
Ivan Mich am 2 Mär. 2021
Bearbeitet: Jan am 2 Mär. 2021
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 Kommentare
Jan
Jan am 2 Mär. 2021
"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 am 2 Mär. 2021
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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 2 Mär. 2021
Bearbeitet: Jan am 2 Mär. 2021
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

Weitere Antworten (0)

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by