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