How to open file, clear content, rewrite conent and close.
31 ビュー (過去 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!!
0 件のコメント
採用された回答
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
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')
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で File Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!