Borrar filtros
Borrar filtros

How to open file, clear content, rewrite conent and close.

39 visualizaciones (últimos 30 días)
Wesser
Wesser el 31 de Ag. de 2022
Comentada: Wesser el 1 de Sept. de 2022
Hi,
I'm trying to open a .dir file (same as a .txt file) clear the content, rewrite the content and then close. The content is different paths to files, which are a combination of numbers and letters. As currently scripted, the .dir file gets rewritten with a series of numbers ...so there is something wrong with the notation, but I'm not sure what. Also, this script creates another level_01 file, but I don't need it to...
for i=1:num_sim
% Rewrite level_01.dir with new file path for each MC iteration
DIR_working = sprintf('%s%d','C:\Users\jessi\Desktop\HydrusMC\Simulations\MC_',i);
% Print the file path of HYDRUS-1D input files in LEVEL_01.dir
DIR=fopen('C:\Users\jessi\Desktop\HydrusMC\LEVEL_01.dir','wt+');
fprintf(DIR,'%f',DIR_working);
fclose(DIR);
end
thanks for any suggestions!!

Respuesta aceptada

Walter Roberson
Walter Roberson el 31 de Ag. de 2022
DIR=fopen('C:\Users\jessi\Desktop\HydrusMC\LEVEL_01.dir','wt+');
That looks for a file named C:\Users\jessi\Desktop\HydrusMC\LEVEL_01.dir . If it does not find it, it creates the file and opens it for reading and writing. If it does find the file, it opens the file for reading and writing and discards all existing content in the file.
DIR_working = sprintf('%s%d','C:\Users\jessi\Desktop\HydrusMC\Simulations\MC_',i);
That is a character vector
fprintf(DIR,'%f',DIR_working);
%f format is "floating point", but what you are passing in is a character vector. The individual characters in the vector will be treated as numbers (using their Unicode code point), and the resulting integers will be output as floating point numbers. You did not specify any space or commas or other delimiters, so the numbers will all run together in the file.
If you want to output a character string use '%s\n' format.

Más respuestas (1)

dpb
dpb el 31 de Ag. de 2022
DIR_working="C:\Users\jessi\Desktop\HydrusMC\Simulations\MC_"+[1:num_sim].';
writematrix(DIR_working,'C:\Users\jessi\Desktop\HydrusMC\LEVEL_01.dir','FileType','text')

Categorías

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

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by