필터 지우기
필터 지우기

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

조회 수: 43 (최근 30일)
Wesser
Wesser 2022년 8월 31일
댓글: Wesser 2022년 9월 1일
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