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 | |
---|
26 | function fail = change_value(value, variableName, filePath) |
---|
27 | % Check for missing inputs |
---|
28 | if 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 |
---|
36 | end |
---|
37 | fail = true; |
---|
38 | % Read in the file |
---|
39 | fh = fopen(filePath, 'rt'); |
---|
40 | if fh < 0 |
---|
41 | return |
---|
42 | end |
---|
43 | fstrm = fread(fh, '*char')'; |
---|
44 | fclose(fh); |
---|
45 | % Find the path |
---|
46 | first_sec = regexp(fstrm, ['[\n\r]+ *' variableName ' += +'], 'end', 'once'); |
---|
47 | second_sec = first_sec + regexp(fstrm(first_sec+1:end), ';? *[\n\r]+', 'once'); |
---|
48 | if isempty(first_sec) || isempty(second_sec) |
---|
49 | return |
---|
50 | end |
---|
51 | % Create the changed line |
---|
52 | if ischar(value) |
---|
53 | str = '''%s'''; |
---|
54 | else |
---|
55 | str = '%1.50g'; |
---|
56 | end |
---|
57 | str = sprintf(str, value); |
---|
58 | % Save the file with the value changed |
---|
59 | fh = fopen(filePath, 'wt'); |
---|
60 | if fh < 0 |
---|
61 | return |
---|
62 | end |
---|
63 | fprintf(fh, '%s%s%s', fstrm(1:first_sec), str, fstrm(second_sec:end)); |
---|
64 | fclose(fh); |
---|
65 | fail = false; |
---|
66 | return |
---|