Concatenate data using fgets

16 visualizaciones (últimos 30 días)
Zhonghao Liao
Zhonghao Liao el 29 de Sept. de 2016
Comentada: Zhonghao Liao el 29 de Sept. de 2016
I want to read a data pattern from a txt file and concatenate each line together. I wrote the following program but the error message shows:
function read_datapattern(filename)
fid = fopen(filename,'rt');
if fid < 0
error('error opening file %s\n\n',filename);
end
pattern = fgets(fid);
for n = 1:32767
nextline = fgets(fid);
pattern = strcat(pattern, nextline);
fprintf(pattern);
fprintf('\n');
fclose(fid);
end
"Invalid file identifier. Use fopen to generate a valid file identifier." "nextline = fgets(fid);"
How do I need to modify the program? Thank you~

Respuesta aceptada

KSSV
KSSV el 29 de Sept. de 2016
Editada: KSSV el 29 de Sept. de 2016
You are closing the file in the loop. close the file after the loop. I assume the below should work.
function read_datapattern(filename)
fid = fopen(filename,'rt');
if fid < 0
error('error opening file %s\n\n',filename);
end
pattern = fgets(fid);
for n = 1:32767
nextline = fgets(fid);
pattern = strcat(pattern, nextline);
fprintf(pattern);
fprintf('\n');
end
fclose(fid);
  1 comentario
Zhonghao Liao
Zhonghao Liao el 29 de Sept. de 2016
Yes, that is work. Thank you~

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre File Operations en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by