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

59 次查看(过去 30 天)
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!!

采纳的回答

Walter Roberson
Walter Roberson 2022-8-31
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.

更多回答(1 个)

dpb
dpb 2022-8-31
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')

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

标签

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by