source: MML/trunk/machine/SOLEIL/common/toolbox/export_fig/change_value.m @ 4

Last change on this file since 4 was 4, checked in by zhangj, 11 years ago

Initial import--MML version from SOLEIL@2013

File size: 1.9 KB
Line 
1%CHANGE_VALUE  Change the value assigned to a unique variable in a file
2%
3% Examples:
4%   fail = change_value(value)
5%   fail = change_value(value, variableName)
6%   fail = change_value(value, variableName, filePath)
7%
8% Function to change the value assigned to a variable in a text file. The
9% assignment must exist already, and must be on a line on its own. For
10% example:
11%    variableName = 'string';
12%    variableName = -0.756e-8;
13% Note that there must be one or more spaces either side of the = sign.
14% Only the first such assignment is changed.
15%
16% IN:
17%   value - The value to be assigned to the variable.
18%   variableName - String containing the name of the variable whose value
19%                  is to be set. Default: name of variable given as value.
20%   filePath - Full path of the file to change. Default: path of calling
21%              file.
22%
23% OUT:
24%   fail - true if change failed, false otherwise.
25
26function fail = change_value(value, variableName, filePath)
27% Check for missing inputs
28if nargin < 3
29    % Get the filename of the calling function
30    filePath = dbstack;
31    filePath = which(filePath(2).file);
32    if nargin < 2
33        % Get the variable name
34        variableName = inputname(1);
35    end
36end
37fail = true;
38% Read in the file
39fh = fopen(filePath, 'rt');
40if fh < 0
41    return
42end
43fstrm = fread(fh, '*char')';
44fclose(fh);
45% Find the path
46first_sec = regexp(fstrm, ['[\n\r]+ *' variableName ' += +'], 'end', 'once');
47second_sec = first_sec + regexp(fstrm(first_sec+1:end), ';? *[\n\r]+', 'once');
48if isempty(first_sec) || isempty(second_sec)
49    return
50end
51% Create the changed line
52if ischar(value)
53    str = '''%s''';
54else
55    str = '%1.50g';
56end
57str = sprintf(str, value);
58% Save the file with the value changed
59fh = fopen(filePath, 'wt');
60if fh < 0
61    return
62end
63fprintf(fh, '%s%s%s', fstrm(1:first_sec), str, fstrm(second_sec:end));
64fclose(fh);
65fail = false;
66return
Note: See TracBrowser for help on using the repository browser.