Search code examples
matlabiosavefile-copying

Save current state of .m file, write to file later (Matlab)


My question: can I save the state of an .m file as a variable, for writing to file at a later point in the code?

Currently, I have these lines:

source_file     = mfilename('fullpath');
write_path      = '~/data';

(code that takes many minutes to execute)

copyfile([source_file,'.m'],[write_path,'/source_file.m']);

The issue is that, during the minutes or hours of code execution, I will make many edits to the original .m code. When copyfile is called at the end of the file, it saves the modified code instead of the one that was executed. I realize of course I could call copyfile before the bulk of the code, but I'd prefer not to do that.


Solution

  • The file that is loaded in memory is still the original file but the file on disk is now the modified file. Your best bet is going to be either to call copyfile at the beginning of your code (not sure why you can't do this). If you really can't do that for some reason, you could read the source code using fread and then write that same string out to the other file after the script has completed.

    fid = fopen(source_file, 'r');
    source_code = fread(fid);
    fclose(fid);
    
    % Do stuff
    
    fout = fopen(fullfile(write_path, 'source_file.m'), 'w');
    fwrite(fout, source_code);
    fclose(fout)