-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_string.m
84 lines (81 loc) · 2.28 KB
/
user_string.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
%USER_STRING Get/set a user specific string
%
% Examples:
% string = user_string(string_name)
% saved = user_string(string_name, new_string)
%
% Function to get and set a string in a system or user specific file. This
% enables, for example, system specific paths to binaries to be saved.
%
% IN:
% string_name - String containing the name of the string required. The
% string is extracted from a file called (string_name).txt,
% stored in the same directory as user_string.m.
% new_string - The new string to be saved under the name given by
% string_name.
%
% OUT:
% string - The currently saved string. Default: ''.
% saved - Boolean indicating whether the save was succesful
% Copyright (C) Oliver Woodford 2011
% This method of saving paths avoids changing .m files which might be in a
% version control system. Instead it saves the user dependent paths in
% separate files with a .txt extension, which need not be checked in to
% the version control system. Thank you to Jonas Dorn for suggesting this
% approach.
function string = user_string(string_name, string)
if ~ischar(string_name)
error('string_name must be a string.');
end
% Create the full filename
string_name = fullfile(fileparts(mfilename('fullpath')), '.ignore', [string_name '.txt']);
if nargin > 1
% Set string
if ~ischar(string)
error('new_string must be a string.');
end
% Make sure the save directory exists
dname = fileparts(string_name);
if ~exist(dname, 'dir')
% Create the directory
try
if ~mkdir(dname)
string = false;
return
end
catch
string = false;
return
end
% Make it hidden
try
fileattrib(dname, '+h');
catch
end
end
% Write the file
fid = fopen(string_name, 'w');
if fid == -1
string = false;
return
end
try
fwrite(fid, string, '*char');
catch
fclose(fid);
string = false;
return
end
fclose(fid);
string = true;
else
% Get string
fid = fopen(string_name, 'r');
if fid == -1
string = '';
return
end
string = fread(fid, '*char')';
fclose(fid);
end
return