]> Creatis software - CreaPhase.git/blob - octave_packages/m/io/fileread.m
update packages
[CreaPhase.git] / octave_packages / m / io / fileread.m
1 ## Copyright (C) 2010-2012 VZLU Prague
2 ##
3 ## This file is part of Octave.
4 ##
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
9 ##
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 ## General Public License for more details.
14 ##
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING.  If not, see
17 ## <http://www.gnu.org/licenses/>.
18
19 ## -*- texinfo -*-
20 ## @deftypefn {Function File} {@var{str} =} fileread (@var{filename})
21 ## Read the contents of @var{filename} and return it as a string.
22 ## @seealso{fread, textread, sscanf}
23 ## @end deftypefn
24
25 function str = fileread (filename)
26
27   if (nargin != 1)
28     print_usage ();
29   endif
30
31   if (! ischar (filename))
32     error ("fileread: FILENAME argument must be a string");
33   endif
34
35   fid = fopen (filename, "r");
36   if (fid < 0)
37     error ("fileread: cannot open file");
38   endif
39
40   unwind_protect
41     str = fread (fid, "*char");
42   unwind_protect_cleanup
43     fclose (fid);
44   end_unwind_protect
45
46 endfunction
47
48
49 %!test
50 %! cstr = {"Hello World", "The answer is 42", "Goodbye World"};
51 %! fname = tmpnam ();
52 %! fid = fopen (fname, "w");
53 %! fprintf (fid, "%s\n", cstr{:})
54 %! fclose (fid);
55 %! str = fileread (fname);
56 %! assert (str', [cstr{1} "\n" cstr{2} "\n" cstr{3} "\n"]);
57 %! unlink (fname);
58
59 %% Test input validation
60 %!error fileread ()
61 %!error fileread (1, 2)
62 %!error <FILENAME argument must be a string> fileread (1)
63