How to open a file and search for a specific parameter for it then change it and save and close?

1 次查看(过去 30 天)
hey so I got a Fortran file that I need to keep opening it for 400 times and keep changing two parameters inside of the file each time.i am planning to use fopen with write permission to do so.However, I am not sure what should I do next. I am not sure how things work when i am searching inside of a file thanks

采纳的回答

Jan
Jan 2018-4-20
编辑:Jan 2018-4-20

It is a very bad idea to modify a source code 400 times to modify a parameter. What about using a loop to modify the parameter inside the code? Compiling the Fortran code repeatedly is a waste of time.

But it is possible:

Str   = fileread(FileName);
CStr  = strsplit(Str, '\n');
Match = strncmp(CStr, 'Param =', 7);
CStr{Match} = sprintf('Param = %g', rand);
fid   = fopen(FileName, 'w');
if fid == -1
  error('Cannot open file: %s', FileName);
end
fprintf(fid, '%s\n', CStr{:});
fclose(fid);

This changes the line starting with "Param =".

更多回答(1 个)

mostafa haggag
mostafa haggag 2018-4-20
thank you so much it is working I am running 200 simulations so I need to change this parameter 200 times to check what is happening using the 200 results. i know it would be easier to change the parameter using fortran but i need a new value for each simulation

类别

Help CenterFile Exchange 中查找有关 Fortran with MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by