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