-
Notifications
You must be signed in to change notification settings - Fork 365
/
read_write_entire_textfile.m
37 lines (36 loc) · 961 Bytes
/
read_write_entire_textfile.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
%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory
%
% Read or write an entire text file to/from memory, without leaving the
% file open if an error occurs.
%
% Reading:
% fstrm = read_write_entire_textfile(fname)
% Writing:
% read_write_entire_textfile(fname, fstrm)
%
%IN:
% fname - Pathname of text file to be read in.
% fstrm - String to be written to the file, including carriage returns.
%
%OUT:
% fstrm - String read from the file. If an fstrm input is given the
% output is the same as that input.
function fstrm = read_write_entire_textfile(fname, fstrm)
modes = {'rt', 'wt'};
writing = nargin > 1;
fh = fopen(fname, modes{1+writing});
if fh == -1
error('Unable to open file %s.', fname);
end
try
if writing
fwrite(fh, fstrm, 'char*1');
else
fstrm = fread(fh, '*char')';
end
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end