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

57 vues (au cours des 30 derniers jours)
Wesser
Wesser le 31 Août 2022
Commenté : Wesser le 1 Sep 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!!

Réponse acceptée

Walter Roberson
Walter Roberson le 31 Août 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.

Plus de réponses (1)

dpb
dpb le 31 Août 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')

Catégories

En savoir plus sur File Operations dans Help Center et File Exchange

Tags

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by