GNU Octave  4.4.1
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
file-io.cc
Go to the documentation of this file.
1 /*
2 
3 Copyright (C) 1993-2018 John W. Eaton
4 
5 This file is part of Octave.
6 
7 Octave is free software: you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11 
12 Octave is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with Octave; see the file COPYING. If not, see
19 <https://www.gnu.org/licenses/>.
20 
21 */
22 
23 // Originally written by John C. Campbell <jcc@bevo.che.wisc.edu>
24 //
25 // Thomas Baier <baier@ci.tuwien.ac.at> added the original versions of
26 // the following functions:
27 //
28 // popen
29 // pclose
30 // execute (now popen2.m)
31 // sync_system (now merged with system)
32 // async_system (now merged with system)
33 
34 // Extensively revised by John W. Eaton <jwe@octave.org>,
35 // April 1996.
36 
37 #if defined (HAVE_CONFIG_H)
38 # include "config.h"
39 #endif
40 
41 #include <cerrno>
42 #include <cstdio>
43 
44 #include <iostream>
45 #include <limits>
46 #include <stack>
47 #include <string>
48 #include <vector>
49 
50 #if defined (HAVE_ZLIB_H)
51 # include <zlib.h>
52 #endif
53 
54 #include "file-ops.h"
55 #include "file-stat.h"
56 #include "lo-ieee.h"
57 #include "mkostemp-wrapper.h"
58 #include "oct-env.h"
59 #include "oct-locbuf.h"
60 #include "tmpfile-wrapper.h"
61 #include "unistd-wrappers.h"
62 
63 #include "builtin-defun-decls.h"
64 #include "defun.h"
65 #include "error.h"
66 #include "errwarn.h"
67 #include "file-io.h"
68 #include "interpreter.h"
69 #include "load-path.h"
70 #include "oct-fstrm.h"
71 #include "oct-iostrm.h"
72 #include "oct-map.h"
73 #include "oct-prcstrm.h"
74 #include "oct-stream.h"
75 #include "oct-strstrm.h"
76 #include "ov.h"
77 #include "ovl.h"
78 #include "pager.h"
79 #include "sysdep.h"
80 #include "utils.h"
81 #include "variables.h"
82 
83 // List of files to delete when we exit or crash.
84 //
85 // FIXME: this should really be static,
86 // but that causes problems on some systems.
87 std::stack <std::string> tmp_files;
88 
89 void
91 {
92  tmp_files.push (file);
93 }
94 
95 void
97 {
98  while (! tmp_files.empty ())
99  {
100  std::string filename = tmp_files.top ();
101  tmp_files.pop ();
102  octave_unlink_wrapper (filename.c_str ());
103  }
104 }
105 
106 static void
108 {
109  use_zlib = false;
110 
111  if (! mode.empty ())
112  {
113  // Matlab uses 'A' and 'W' to indicate that buffered writing should
114  // take place. Octave already does that. Theoretically, we should
115  // warn about using 'a', 'r', or 'w' because Octave does not enable
116  // automatic flushing with these modes. The performance hit is ~4X
117  // when using automatic flushing and seems completely unnecessary.
118  // See bug #52644.
119 
120  size_t pos = mode.find ('W');
121 
122  if (pos != std::string::npos)
123  mode[pos] = 'w';
124 
125  pos = mode.find ('R');
126 
127  if (pos != std::string::npos)
128  mode[pos] = 'r';
129 
130  pos = mode.find ('A');
131 
132  if (pos != std::string::npos)
133  mode[pos] = 'a';
134 
135  pos = mode.find ('z');
136 
137  if (pos != std::string::npos)
138  {
139 #if defined (HAVE_ZLIB)
140  use_zlib = true;
141  mode.erase (pos, 1);
142 #else
143  err_disabled_feature ("", "gzipped files (zlib)");
144 #endif
145  }
146 
147  // Use binary mode if 't' is not specified, but don't add
148  // 'b' if it is already present.
149 
150  size_t bpos = mode.find ('b');
151  size_t tpos = mode.find ('t');
152 
153  if (bpos == std::string::npos && tpos == std::string::npos)
154  mode += 'b';
155  }
156 }
157 
158 static std::ios::openmode
160 {
161  std::ios::openmode retval = std::ios::in;
162 
163  if (mode == "rt")
164  retval = std::ios::in;
165  else if (mode == "wt")
166  retval = std::ios::out | std::ios::trunc;
167  else if (mode == "at")
168  retval = std::ios::out | std::ios::app;
169  else if (mode == "r+t" || mode == "rt+")
170  retval = std::ios::in | std::ios::out;
171  else if (mode == "w+t" || mode == "wt+")
172  retval = std::ios::in | std::ios::out | std::ios::trunc;
173  else if (mode == "a+t" || mode == "at+")
174  retval = std::ios::in | std::ios::out | std::ios::app;
175  else if (mode == "rb" || mode == "r")
176  retval = std::ios::in | std::ios::binary;
177  else if (mode == "wb" || mode == "w")
178  retval = std::ios::out | std::ios::trunc | std::ios::binary;
179  else if (mode == "ab" || mode == "a")
180  retval = std::ios::out | std::ios::app | std::ios::binary;
181  else if (mode == "r+b" || mode == "rb+" || mode == "r+")
182  retval = std::ios::in | std::ios::out | std::ios::binary;
183  else if (mode == "w+b" || mode == "wb+" || mode == "w+")
184  retval = (std::ios::in | std::ios::out | std::ios::trunc
185  | std::ios::binary);
186  else if (mode == "a+b" || mode == "ab+" || mode == "a+")
187  retval = (std::ios::in | std::ios::out | std::ios::app
188  | std::ios::binary);
189  else
190  error ("invalid mode specified");
191 
192  return retval;
193 }
194 
195 DEFMETHOD (fclose, interp, args, ,
196  doc: /* -*- texinfo -*-
197 @deftypefn {} {} fclose (@var{fid})
198 @deftypefnx {} {} fclose ("all")
199 @deftypefnx {} {@var{status} =} fclose ("all")
200 Close the file specified by the file descriptor @var{fid}.
201 
202 If successful, @code{fclose} returns 0, otherwise, it returns -1. The
203 second form of the @code{fclose} call closes all open files except
204 @code{stdin}, @code{stdout}, @code{stderr}, and any FIDs associated
205 with gnuplot.
206 @seealso{fopen, fflush, freport}
207 @end deftypefn */)
208 {
209  if (args.length () != 1)
210  print_usage ();
211 
212  octave::stream_list& streams = interp.get_stream_list ();
213 
214  return ovl (streams.remove (args(0), "fclose"));
215 }
216 
217 DEFMETHOD (fclear, interp, args, ,
218  doc: /* -*- texinfo -*-
219 @deftypefn {} {} fclear (@var{fid})
220 Clear the stream state for the file specified by the file descriptor
221 @var{fid}.
222 @seealso{ferror, fopen}
223 @end deftypefn */)
224 {
225  if (args.length () != 1)
226  print_usage ();
227 
228  octave::stream_list& streams = interp.get_stream_list ();
229 
230  int fid = streams.get_file_number (args(0));
231 
232  octave::stream os = streams.lookup (fid, "fclear");
233 
234  os.clearerr ();
235 
236  return ovl ();
237 }
238 
239 DEFMETHOD (fflush, interp, args, ,
240  doc: /* -*- texinfo -*-
241 @deftypefn {} {} fflush (@var{fid})
242 Flush output to file descriptor @var{fid}.
243 
244 @code{fflush} returns 0 on success and an OS dependent error value
245 (@minus{}1 on Unix) on error.
246 
247 Programming Note: Flushing is useful for ensuring that all pending output
248 makes it to the screen before some other event occurs. For example, it is
249 always a good idea to flush the standard output stream before calling
250 @code{input}.
251 @seealso{fopen, fclose}
252 @end deftypefn */)
253 {
254  if (args.length () != 1)
255  print_usage ();
256 
257  octave_value retval = -1;
258 
259  octave::stream_list& streams = interp.get_stream_list ();
260 
261  // FIXME: any way to avoid special case for stdout?
262  int fid = streams.get_file_number (args(0));
263 
264  if (fid == 1)
265  {
267 
268  retval = 0;
269  }
270  else
271  {
272  octave::stream os = streams.lookup (fid, "fflush");
273 
274  retval = os.flush ();
275  }
276 
277  return retval;
278 }
279 
280 DEFMETHOD (fgetl, interp, args, ,
281  doc: /* -*- texinfo -*-
282 @deftypefn {} {@var{str} =} fgetl (@var{fid})
283 @deftypefnx {} {@var{str} =} fgetl (@var{fid}, @var{len})
284 Read characters from a file, stopping after a newline, or EOF,
285 or @var{len} characters have been read.
286 
287 The characters read, excluding the possible trailing newline, are returned
288 as a string.
289 
290 If @var{len} is omitted, @code{fgetl} reads until the next newline
291 character.
292 
293 If there are no more characters to read, @code{fgetl} returns @minus{}1.
294 
295 To read a line and return the terminating newline see @code{fgets}.
296 @seealso{fgets, fscanf, fread, fopen}
297 @end deftypefn */)
298 {
299  static std::string who = "fgetl";
300 
301  int nargin = args.length ();
302 
304  print_usage ();
305 
306  octave::stream_list& streams = interp.get_stream_list ();
307 
308  octave::stream os = streams.lookup (args(0), who);
309 
310  octave_value len_arg = (nargin == 2) ? args(1) : octave_value ();
311 
312  bool err = false;
313 
314  std::string tmp = os.getl (len_arg, err, who);
315 
316  if (! err)
317  return ovl (tmp, tmp.length ());
318  else
319  return ovl (-1, 0);
320 }
321 
322 DEFMETHOD (fgets, interp, args, ,
323  doc: /* -*- texinfo -*-
324 @deftypefn {} {@var{str} =} fgets (@var{fid})
325 @deftypefnx {} {@var{str} =} fgets (@var{fid}, @var{len})
326 Read characters from a file, stopping after a newline, or EOF,
327 or @var{len} characters have been read.
328 
329 The characters read, including the possible trailing newline, are returned
330 as a string.
331 
332 If @var{len} is omitted, @code{fgets} reads until the next newline
333 character.
334 
335 If there are no more characters to read, @code{fgets} returns @minus{}1.
336 
337 To read a line and discard the terminating newline see @code{fgetl}.
338 @seealso{fputs, fgetl, fscanf, fread, fopen}
339 @end deftypefn */)
340 {
341  static std::string who = "fgets";
342 
343  int nargin = args.length ();
344 
346  print_usage ();
347 
348  octave::stream_list& streams = interp.get_stream_list ();
349 
350  octave::stream os = streams.lookup (args(0), who);
351 
352  octave_value len_arg = (nargin == 2) ? args(1) : octave_value ();
353 
354  bool err = false;
355 
356  std::string tmp = os.gets (len_arg, err, who);
357 
358  if (! err)
359  return ovl (tmp, tmp.length ());
360  else
361  return ovl (-1.0, 0.0);
362 }
363 
364 DEFMETHOD (fskipl, interp, args, ,
365  doc: /* -*- texinfo -*-
366 @deftypefn {} {@var{nlines} =} fskipl (@var{fid})
367 @deftypefnx {} {@var{nlines} =} fskipl (@var{fid}, @var{count})
368 @deftypefnx {} {@var{nlines} =} fskipl (@var{fid}, Inf)
369 Read and skip @var{count} lines from the file specified by the file
370 descriptor @var{fid}.
371 
372 @code{fskipl} discards characters until an end-of-line is encountered
373 exactly @var{count}-times, or until the end-of-file marker is found.
374 
375 If @var{count} is omitted, it defaults to 1. @var{count} may also be
376 @code{Inf}, in which case lines are skipped until the end of the file.
377 This form is suitable for counting the number of lines in a file.
378 
379 Returns the number of lines skipped (end-of-line sequences encountered).
380 @seealso{fgetl, fgets, fscanf, fopen}
381 @end deftypefn */)
382 {
383  static std::string who = "fskipl";
384 
385  int nargin = args.length ();
386 
388  print_usage ();
389 
390  octave::stream_list& streams = interp.get_stream_list ();
391 
392  octave::stream os = streams.lookup (args(0), who);
393 
394  octave_value count_arg = (nargin == 2) ? args(1) : octave_value ();
395 
396  bool err = false;
397 
398  off_t tmp = os.skipl (count_arg, err, who);
399 
400  if (! err)
401  return ovl (tmp);
402  else
403  return ovl ();
404 }
405 
406 static octave::stream
407 do_stream_open (const std::string& name, const std::string& mode_arg,
408  const std::string& arch, int& fid)
409 {
411 
412  fid = -1;
413 
414  std::string mode = mode_arg;
415  bool use_zlib = false;
417 
418  std::ios::openmode md = fopen_mode_to_ios_mode (mode);
419 
422 
424 
426 
427  if (! (md & std::ios::out))
429 
430  if (! fs.is_dir ())
431  {
432 #if defined (HAVE_ZLIB)
433  if (use_zlib)
434  {
435  FILE *fptr = std::fopen (fname.c_str (), mode.c_str ());
436 
437  int fd = fileno (fptr);
438 
439  gzFile gzf = ::gzdopen (fd, mode.c_str ());
440 
441  if (fptr)
443  md, flt_fmt);
444  else
445  retval.error (std::strerror (errno));
446  }
447  else
448 #endif
449  {
450  FILE *fptr = std::fopen (fname.c_str (), mode.c_str ());
451 
453  flt_fmt);
454 
455  if (! fptr)
456  retval.error (std::strerror (errno));
457  }
458 
459  }
460 
461  return retval;
462 }
463 
464 static octave::stream
465 do_stream_open (const octave_value& tc_name, const octave_value& tc_mode,
466  const octave_value& tc_arch, const char *fcn, int& fid)
467 {
469 
470  fid = -1;
471 
472  std::string name = tc_name.xstring_value ("%s: filename must be a string", fcn);
473  std::string mode = tc_mode.xstring_value ("%s: file mode must be a string", fcn);
474  std::string arch = tc_arch.xstring_value ("%s: architecture type must be a string", fcn);
475 
476  retval = do_stream_open (name, mode, arch, fid);
477 
478  return retval;
479 }
480 
481 DEFMETHOD (fopen, interp, args, nargout,
482  doc: /* -*- texinfo -*-
483 @deftypefn {} {@var{fid} =} fopen (@var{name})
484 @deftypefnx {} {@var{fid} =} fopen (@var{name}, @var{mode})
485 @deftypefnx {} {@var{fid} =} fopen (@var{name}, @var{mode}, @var{arch})
486 @deftypefnx {} {[@var{fid}, @var{msg}] =} fopen (@dots{})
487 @deftypefnx {} {@var{fid_list} =} fopen ("all")
488 @deftypefnx {} {[@var{file}, @var{mode}, @var{arch}] =} fopen (@var{fid})
489 Open a file for low-level I/O or query open files and file descriptors.
490 
491 The first form of the @code{fopen} function opens the named file with
492 the specified mode (read-write, read-only, etc.@:) and architecture
493 interpretation (IEEE big endian, IEEE little endian, etc.), and returns
494 an integer value that may be used to refer to the file later. If an
495 error occurs, @var{fid} is set to @minus{}1 and @var{msg} contains the
496 corresponding system error message. The @var{mode} is a one or two
497 character string that specifies whether the file is to be opened for
498 reading, writing, or both.
499 
500 The second form of the @code{fopen} function returns a vector of file ids
501 corresponding to all the currently open files, excluding the
502 @code{stdin}, @code{stdout}, and @code{stderr} streams.
503 
504 The third form of the @code{fopen} function returns information about the
505 open file given its file id.
506 
507 For example,
508 
509 @example
510 myfile = fopen ("splat.dat", "r", "ieee-le");
511 @end example
512 
513 @noindent
514 opens the file @file{splat.dat} for reading. If necessary, binary
515 numeric values will be read assuming they are stored in IEEE format with
516 the least significant bit first, and then converted to the native
517 representation.
518 
519 Opening a file that is already open simply opens it again and returns a
520 separate file id. It is not an error to open a file several times,
521 though writing to the same file through several different file ids may
522 produce unexpected results.
523 
524 The possible values of @var{mode} are
525 
526 @table @asis
527 @item @samp{r} (default)
528 Open a file for reading.
529 
530 @item @samp{w}
531 Open a file for writing. The previous contents are discarded.
532 
533 @item @samp{a}
534 Open or create a file for writing at the end of the file.
535 
536 @item @samp{r+}
537 Open an existing file for reading and writing.
538 
539 @item @samp{w+}
540 Open a file for reading or writing. The previous contents are
541 discarded.
542 
543 @item @samp{a+}
544 Open or create a file for reading or writing at the end of the
545 file.
546 @end table
547 
548 Append a @qcode{"t"} to the mode string to open the file in text mode or a
549 @qcode{"b"} to open in binary mode. On Windows systems,
550 text mode reading and writing automatically converts linefeeds to the
551 appropriate line end character for the system (carriage-return linefeed on
552 Windows). The default when no mode is specified is binary.
553 
554 Additionally, you may append a @qcode{"z"} to the mode string to open a
555 gzipped file for reading or writing. For this to be successful, you
556 must also open the file in binary mode.
557 
558 The parameter @var{arch} is a string specifying the default data format
559 for the file. Valid values for @var{arch} are:
560 
561 @table @asis
562 @item @qcode{"native"} or @qcode{"n"} (default)
563 The format of the current machine.
564 
565 @item @qcode{"ieee-be"} or @qcode{"b"}
566 IEEE big endian format.
567 
568 @item @qcode{"ieee-le"} or @qcode{"l"}
569 IEEE little endian format.
570 @end table
571 
572 @noindent
573 However, conversions are currently only supported for @samp{native},
574 @samp{ieee-be}, and @samp{ieee-le} formats.
575 
576 When opening a new file that does not yet exist, permissions will be set to
577 @code{0666 - @var{umask}}.
578 
579 Compatibility Note: Octave opens files using buffered I/O. Small writes are
580 accumulated until an internal buffer is filled, and then everything is written
581 in a single operation. This is very efficient and improves performance.
582 @sc{matlab}, however, opens files using flushed I/O where every write operation
583 is immediately performed. If the write operation must be performed immediately
584 after data has been written then the write should be followed by a call to
585 @code{fflush} to flush the internal buffer.
586 @seealso{fclose, fgets, fgetl, fscanf, fread, fputs, fdisp, fprintf, fwrite, fskipl, fseek, frewind, ftell, feof, ferror, fclear, fflush, freport, umask}
587 @end deftypefn */)
588 {
589  int nargin = args.length ();
590 
592  print_usage ();
593 
595 
596  octave::stream_list& streams = interp.get_stream_list ();
597 
598  if (nargin == 1)
599  {
600  if (args(0).is_string ())
601  {
602  // If there is only one argument and it is a string but it
603  // is not the string "all", we assume it is a file to open
604  // with MODE = "r". To open a file called "all", you have
605  // to supply more than one argument.
606  if (nargout < 2 && args(0).string_value () == "all")
607  return streams.open_file_numbers ();
608  }
609  else
610  {
611  string_vector tmp = streams.get_info (args(0));
612 
613  retval = ovl (tmp(0), tmp(1), tmp(2));
614 
615  return retval;
616  }
617  }
618 
619  octave_value mode = (nargin == 2 || nargin == 3)
620  ? args(1) : octave_value ("r");
621 
623  ? args(2) : octave_value ("native");
624 
625  int fid = -1;
626 
627  octave::stream os = do_stream_open (args(0), mode, arch, "fopen", fid);
628 
629  if (os)
630  retval = ovl (streams.insert (os), "");
631  else
632  {
633  int error_number = 0;
634 
635  retval = ovl (-1.0, os.error (false, error_number));
636  }
637 
638  return retval;
639 }
640 
641 /*
642 ## FIXME: Only have tests for query mode. Need others for regular fopen call.
643 %!test # Uses hardcoded value of 1 for stdout
644 %! [name, mode, arch] = fopen (1);
645 %! assert (name, "stdout");
646 %! assert (mode, "w");
647 
648 %!test # Query of non-existent stream returns all ""
649 %! [name, mode, arch] = fopen (-1);
650 %! assert (name, "");
651 %! assert (mode, "");
652 %! assert (arch, "");
653 */
654 
655 DEFMETHOD (freport, interp, args, ,
656  doc: /* -*- texinfo -*-
657 @deftypefn {} {} freport ()
658 Print a list of which files have been opened, and whether they are open
659 for reading, writing, or both.
660 
661 For example:
662 
663 @example
664 @group
665 freport ()
666 
667  @print{} number mode arch name
668  @print{} ------ ---- ---- ----
669  @print{} 0 r ieee-le stdin
670  @print{} 1 w ieee-le stdout
671  @print{} 2 w ieee-le stderr
672  @print{} 3 r ieee-le myfile
673 @end group
674 @end example
675 @seealso{fopen, fclose, is_valid_file_id}
676 @end deftypefn */)
677 {
678  if (args.length () > 0)
679  warning ("freport: ignoring extra arguments");
680 
681  octave::stream_list& streams = interp.get_stream_list ();
682 
684 
685  return ovl ();
686 }
687 
688 DEFMETHOD (frewind, interp, args, nargout,
689  doc: /* -*- texinfo -*-
690 @deftypefn {} {} frewind (@var{fid})
691 @deftypefnx {} {@var{status} =} frewind (@var{fid})
692 Move the file pointer to the beginning of the file specified by file
693 descriptor @var{fid}.
694 
695 @code{frewind} returns 0 for success, and -1 if an error is encountered. It
696 is equivalent to @code{fseek (@var{fid}, 0, SEEK_SET)}.
697 @seealso{fseek, ftell, fopen}
698 @end deftypefn */)
699 {
700  if (args.length () != 1)
701  print_usage ();
702 
703  int result = -1;
704 
705  octave::stream_list& streams = interp.get_stream_list ();
706 
707  octave::stream os = streams.lookup (args(0), "frewind");
708 
709  result = os.rewind ();
710 
711  if (nargout > 0)
712  return ovl (result);
713  else
714  return ovl ();
715 }
716 
717 DEFMETHOD (fseek, interp, args, ,
718  doc: /* -*- texinfo -*-
719 @deftypefn {} {} fseek (@var{fid}, @var{offset})
720 @deftypefnx {} {} fseek (@var{fid}, @var{offset}, @var{origin})
721 @deftypefnx {} {@var{status} =} fseek (@dots{})
722 Set the file pointer to the location @var{offset} within the file @var{fid}.
723 
724 The pointer is positioned @var{offset} characters from the @var{origin}, which
725 may be one of the predefined variables @w{@qcode{SEEK_SET}} (beginning),
726 @w{@qcode{SEEK_CUR}} (current position), or @w{@qcode{SEEK_END}} (end of file)
727 or strings @nospell{@qcode{"bof"}}, @nospell{@qcode{"cof"}}, or
728 @nospell{@qcode{"eof"}}. If @var{origin} is omitted, @w{@qcode{SEEK_SET}} is
729 assumed. @var{offset} may be positive, negative, or zero but not all
730 combinations of @var{origin} and @var{offset} can be realized.
731 
732 @code{fseek} returns 0 on success and -1 on error.
733 @seealso{fskipl, frewind, ftell, fopen, SEEK_SET, SEEK_CUR, SEEK_END}
734 @end deftypefn */)
735 {
736  int nargin = args.length ();
737 
739  print_usage ();
740 
741  octave::stream_list& streams = interp.get_stream_list ();
742 
743  octave::stream os = streams.lookup (args(0), "fseek");
744 
745  octave_value origin_arg = (nargin == 3) ? args(2) : octave_value (-1.0);
746 
747  return ovl (os.seek (args(1), origin_arg));
748 }
749 
750 DEFMETHOD (ftell, interp, args, ,
751  doc: /* -*- texinfo -*-
752 @deftypefn {} {@var{pos} =} ftell (@var{fid})
753 Return the position of the file pointer as the number of characters from the
754 beginning of the file specified by file descriptor @var{fid}.
755 @seealso{fseek, frewind, feof, fopen}
756 @end deftypefn */)
757 {
758  if (args.length () != 1)
759  print_usage ();
760 
761  octave::stream_list& streams = interp.get_stream_list ();
762 
763  octave::stream os = streams.lookup (args(0), "ftell");
764 
765  return ovl (os.tell ());
766 }
767 
768 static octave_value_list
769 printf_internal (octave::interpreter& interp, const std::string& who,
770  const octave_value_list& args, int nargout)
771 {
772  int nargin = args.length ();
773 
774  if (! (nargin > 1 || (nargin > 0 && args(0).is_string ())))
775  print_usage ();
776 
777  int result;
778 
780  int fmt_n = 0;
781 
783 
784  if (args(0).is_string ())
785  os = streams.lookup (1, who);
786  else
787  {
788  fmt_n = 1;
789  os = streams.lookup (args(0), who);
790  }
791 
792  if (! args(fmt_n).is_string ())
793  error ("%s: format TEMPLATE must be a string", who.c_str ());
794 
795  octave_value_list tmp_args;
796 
797  if (nargin > 1 + fmt_n)
798  {
799  tmp_args.resize (nargin-fmt_n-1, octave_value ());
800 
801  for (int i = fmt_n + 1; i < nargin; i++)
802  tmp_args(i-fmt_n-1) = args(i);
803  }
804 
805  result = os.printf (args(fmt_n), tmp_args, who);
806 
807  if (nargout > 0)
808  return ovl (result);
809  else
810  return ovl ();
811 }
812 
813 DEFMETHOD (fprintf, interp, args, nargout,
814  doc: /* -*- texinfo -*-
815 @deftypefn {} {} fprintf (@var{fid}, @var{template}, @dots{})
816 @deftypefnx {} {} fprintf (@var{template}, @dots{})
817 @deftypefnx {} {@var{numbytes} =} fprintf (@dots{})
818 This function is equivalent to @code{printf}, except that the output is
819 written to the file descriptor @var{fid} instead of @code{stdout}.
820 
821 If @var{fid} is omitted, the output is written to @code{stdout} making the
822 function exactly equivalent to @code{printf}.
823 
824 The optional output returns the number of bytes written to the file.
825 
826 Implementation Note: For compatibility with @sc{matlab}, escape sequences in
827 the template string (e.g., @qcode{"@xbackslashchar{}n"} => newline) are
828 expanded even when the template string is defined with single quotes.
829 @seealso{fputs, fdisp, fwrite, fscanf, printf, sprintf, fopen}
830 @end deftypefn */)
831 {
832  static std::string who = "fprintf";
833 
834  return printf_internal (interp, who, args, nargout);
835 }
836 
837 DEFMETHOD (printf, interp, args, nargout,
838  doc: /* -*- texinfo -*-
839 @deftypefn {} {} printf (@var{template}, @dots{})
840 Print optional arguments under the control of the template string
841 @var{template} to the stream @code{stdout} and return the number of
842 characters printed.
843 @ifclear OCTAVE_MANUAL
844 
845 See the Formatted Output section of the GNU Octave manual for a
846 complete description of the syntax of the template string.
847 @end ifclear
848 
849 Implementation Note: For compatibility with @sc{matlab}, escape sequences in
850 the template string (e.g., @qcode{"@xbackslashchar{}n"} => newline) are
851 expanded even when the template string is defined with single quotes.
852 @seealso{fprintf, sprintf, scanf}
853 @end deftypefn */)
854 {
855  static std::string who = "printf";
856 
857  octave_value_list tmp_args = args;
858 
859  return printf_internal (interp, who, tmp_args.prepend (octave_value (1)),
860  nargout);
861 }
862 
863 static octave_value_list
864 puts_internal (octave::interpreter& interp, const std::string& who,
865  const octave_value_list& args)
866 {
867  if (args.length () != 2)
868  print_usage ();
869 
871 
872  octave::stream os = streams.lookup (args(0), who);
873 
874  return ovl (os.puts (args(1), who));
875 }
876 
877 DEFMETHOD (fputs, interp, args, ,
878  doc: /* -*- texinfo -*-
879 @deftypefn {} {} fputs (@var{fid}, @var{string})
880 @deftypefnx {} {@var{status} =} fputs (@var{fid}, @var{string})
881 Write the string @var{string} to the file with file descriptor @var{fid}.
882 
883 The string is written to the file with no additional formatting. Use
884 @code{fdisp} instead to automatically append a newline character appropriate
885 for the local machine.
886 
887 Return a non-negative number on success or EOF on error.
888 @seealso{fdisp, fprintf, fwrite, fopen}
889 @end deftypefn */)
890 {
891  static std::string who = "fputs";
892 
893  return puts_internal (interp, who, args);
894 }
895 
896 DEFMETHOD (puts, interp, args, ,
897  doc: /* -*- texinfo -*-
898 @deftypefn {} {} puts (@var{string})
899 @deftypefnx {} {@var{status} =} puts (@var{string})
900 Write a string to the standard output with no formatting.
901 
902 The string is written verbatim to the standard output. Use @code{disp} to
903 automatically append a newline character appropriate for the local machine.
904 
905 Return a non-negative number on success and EOF on error.
906 @seealso{fputs, disp}
907 @end deftypefn */)
908 {
909  static std::string who = "puts";
910 
911  octave_value_list tmp_args = args;
912 
913  return puts_internal (interp, who, tmp_args.prepend (octave_value (1)));
914 }
915 
916 DEFUN (sprintf, args, ,
917  doc: /* -*- texinfo -*-
918 @deftypefn {} {} sprintf (@var{template}, @dots{})
919 This is like @code{printf}, except that the output is returned as a
920 string.
921 
922 Unlike the C library function, which requires you to provide a suitably
923 sized string as an argument, Octave's @code{sprintf} function returns the
924 string, automatically sized to hold all of the items converted.
925 
926 Implementation Note: For compatibility with @sc{matlab}, escape sequences in
927 the template string (e.g., @qcode{"@xbackslashchar{}n"} => newline) are
928 expanded even when the template string is defined with single quotes.
929 @seealso{printf, fprintf, sscanf}
930 @end deftypefn */)
931 {
932  static std::string who = "sprintf";
933 
934  int nargin = args.length ();
935 
936  if (nargin == 0)
937  print_usage ();
938 
939  // We don't use octave_ostrstream::create here because need direct
940  // access to the OSTR object so that we can extract a string object
941  // from it to return.
942  octave_ostrstream *ostr = new octave_ostrstream ();
943 
944  // The octave::stream destructor will delete OSTR for us.
945  octave::stream os (ostr);
946 
947  if (! os.is_valid ())
948  error ("%s: unable to create output buffer", who.c_str ());
949 
950  octave_value fmt_arg = args(0);
951 
952  if (! fmt_arg.is_string ())
953  error ("%s: format TEMPLATE must be a string", who.c_str ());
954 
956 
957  octave_value_list tmp_args;
958  if (nargin > 1)
959  {
960  tmp_args.resize (nargin-1, octave_value ());
961 
962  for (int i = 1; i < nargin; i++)
963  tmp_args(i-1) = args(i);
964  }
965 
966  // NOTE: Call to os.error must precede next call to ostr which might reset it.
967  retval(2) = os.printf (fmt_arg, tmp_args, who);
968  retval(1) = os.error ();
969 
970  std::string result = ostr->str ();
971  char type = (fmt_arg.is_sq_string () ? '\'' : '"');
972 
973  retval(0) = (result.empty () ? octave_value (charMatrix (1, 0), type)
974  : octave_value (result, type));
975 
976  return retval;
977 }
978 
979 static octave_value_list
980 scanf_internal (octave::interpreter& interp, const std::string& who,
981  const octave_value_list& args)
982 {
983  int nargin = args.length ();
984 
986  print_usage ();
987 
989 
991 
992  octave::stream os = streams.lookup (args(0), who);
993 
994  if (! args(1).is_string ())
995  error ("%s: format TEMPLATE must be a string", who.c_str ());
996 
997  if (nargin == 3 && args(2).is_string ())
998  {
999  retval = os.oscanf (args(1), who);
1000  }
1001  else
1002  {
1003  octave_idx_type count = 0;
1004 
1005  Array<double> size
1006  = (nargin == 3
1007  ? args(2).vector_value ()
1008  : Array<double> (dim_vector (1, 1), lo_ieee_inf_value ()));
1009 
1010  octave_value tmp = os.scanf (args(1), size, count, who);
1011 
1012  retval = ovl (tmp, count, os.error ());
1013  }
1014 
1015  return retval;
1016 }
1017 
1018 DEFMETHOD (fscanf, interp, args, ,
1019  doc: /* -*- texinfo -*-
1020 @deftypefn {} {[@var{val}, @var{count}, @var{errmsg}] =} fscanf (@var{fid}, @var{template}, @var{size})
1021 @deftypefnx {} {[@var{v1}, @var{v2}, @dots{}, @var{count}, @var{errmsg}] =} fscanf (@var{fid}, @var{template}, "C")
1022 In the first form, read from @var{fid} according to @var{template},
1023 returning the result in the matrix @var{val}.
1024 
1025 The optional argument @var{size} specifies the amount of data to read
1026 and may be one of
1027 
1028 @table @code
1029 @item Inf
1030 Read as much as possible, returning a column vector.
1031 
1032 @item @var{nr}
1033 Read up to @var{nr} elements, returning a column vector.
1034 
1035 @item [@var{nr}, Inf]
1036 Read as much as possible, returning a matrix with @var{nr} rows. If the
1037 number of elements read is not an exact multiple of @var{nr}, the last
1038 column is padded with zeros.
1039 
1040 @item [@var{nr}, @var{nc}]
1041 Read up to @code{@var{nr} * @var{nc}} elements, returning a matrix with
1042 @var{nr} rows. If the number of elements read is not an exact multiple
1043 of @var{nr}, the last column is padded with zeros.
1044 @end table
1045 
1046 @noindent
1047 If @var{size} is omitted, a value of @code{Inf} is assumed.
1048 
1049 A string is returned if @var{template} specifies only character conversions.
1050 
1051 The number of items successfully read is returned in @var{count}.
1052 
1053 If an error occurs, @var{errmsg} contains a system-dependent error message.
1054 
1055 In the second form, read from @var{fid} according to @var{template},
1056 with each conversion specifier in @var{template} corresponding to a
1057 single scalar return value. This form is more ``C-like'', and also
1058 compatible with previous versions of Octave. The number of successful
1059 conversions is returned in @var{count}
1060 @ifclear OCTAVE_MANUAL
1061 
1062 See the Formatted Input section of the GNU Octave manual for a
1063 complete description of the syntax of the template string.
1064 @end ifclear
1065 @seealso{fgets, fgetl, fread, scanf, sscanf, fopen}
1066 @end deftypefn */)
1067 {
1068  static std::string who = "fscanf";
1069 
1070  return scanf_internal (interp, who, args);
1071 }
1072 
1073 static std::string
1074 get_scan_string_data (const octave_value& val, const std::string& who)
1075 {
1077 
1078  if (! val.is_string ())
1079  error ("%s: argument STRING must be a string", who.c_str ());
1080 
1081  octave_value tmp = val.reshape (dim_vector (1, val.numel ()));
1082 
1083  retval = tmp.string_value ();
1084 
1085  return retval;
1086 }
1087 
1088 DEFUN (sscanf, args, ,
1089  doc: /* -*- texinfo -*-
1090 @deftypefn {} {[@var{val}, @var{count}, @var{errmsg}, @var{pos}] =} sscanf (@var{string}, @var{template}, @var{size})
1091 @deftypefnx {} {[@var{v1}, @var{v2}, @dots{}, @var{count}, @var{errmsg}] =} sscanf (@var{string}, @var{template}, "C")
1092 This is like @code{fscanf}, except that the characters are taken from the
1093 string @var{string} instead of from a stream.
1094 
1095 Reaching the end of the string is treated as an end-of-file condition. In
1096 addition to the values returned by @code{fscanf}, the index of the next
1097 character to be read is returned in @var{pos}.
1098 @seealso{fscanf, scanf, sprintf}
1099 @end deftypefn */)
1100 {
1101  static std::string who = "sscanf";
1102 
1103  int nargin = args.length ();
1104 
1105  if (nargin < 2 || nargin > 3)
1106  print_usage ();
1107 
1109 
1110  std::string data = get_scan_string_data (args(0), who);
1111 
1113 
1114  if (! os.is_valid ())
1115  error ("%s: unable to create temporary input buffer", who.c_str ());
1116 
1117  if (! args(1).is_string ())
1118  error ("%s: format TEMPLATE must be a string", who.c_str ());
1119 
1120  if (nargin == 3 && args(2).is_string ())
1121  {
1122  retval = os.oscanf (args(1), who);
1123  }
1124  else
1125  {
1126  octave_idx_type count = 0;
1127 
1128  Array<double> size = (nargin == 3) ? args(2).vector_value ()
1129  : Array<double> (dim_vector (1, 1),
1130  lo_ieee_inf_value ());
1131 
1132  octave_value tmp = os.scanf (args(1), size, count, who);
1133 
1134  // FIXME: is this the right thing to do?
1135  // Extract error message first, because getting
1136  // position will clear it.
1137  std::string errmsg = os.error ();
1138 
1139  retval = ovl (tmp, count, errmsg,
1140  (os.eof () ? data.length () : os.tell ()) + 1);
1141  }
1142 
1143  return retval;
1144 }
1145 
1146 DEFMETHOD (scanf, interp, args, ,
1147  doc: /* -*- texinfo -*-
1148 @deftypefn {} {[@var{val}, @var{count}, @var{errmsg}] =} scanf (@var{template}, @var{size})
1149 @deftypefnx {} {[@var{v1}, @var{v2}, @dots{}, @var{count}, @var{errmsg}] =} scanf (@var{template}, "C")
1150 This is equivalent to calling @code{fscanf} with @var{fid} = @code{stdin}.
1151 
1152 It is currently not useful to call @code{scanf} in interactive programs.
1153 @seealso{fscanf, sscanf, printf}
1154 @end deftypefn */)
1155 {
1156  static std::string who = "scanf";
1157 
1158  octave_value_list tmp_args = args;
1159 
1160  return scanf_internal (interp, who, tmp_args.prepend (octave_value (0)));
1161 }
1162 
1163 static octave_value_list
1164 textscan_internal (octave::interpreter& interp, const std::string& who,
1165  const octave_value_list& args)
1166 {
1167  if (args.length () < 1)
1168  print_usage (who);
1169 
1171 
1172  if (args(0).is_string ())
1173  {
1174  std::string data = get_scan_string_data (args(0), who);
1175 
1176  os = octave_istrstream::create (data);
1177 
1178  if (! os.is_valid ())
1179  error ("%s: unable to create temporary input buffer", who.c_str ());
1180  }
1181  else
1182  {
1184 
1185  os = streams.lookup (args(0), who);
1186  }
1187 
1188  int nskip = 1;
1189 
1190  std::string fmt;
1191 
1192  if (args.length () == 1)
1193  {
1194  // ommited format = %f. explicit "" = width from file
1195  fmt = "%f";
1196  }
1197  else if (args(1).is_string ())
1198  {
1199  fmt = args(1).string_value ();
1200 
1201  if (args(1).is_sq_string ())
1202  fmt = do_string_escapes (fmt);
1203 
1204  nskip++;
1205  }
1206  else
1207  error ("%s: FORMAT must be a string", who.c_str ());
1208 
1209  octave_idx_type ntimes = -1;
1210 
1211  if (args.length () > 2)
1212  {
1213  if (args(2).isnumeric ())
1214  {
1215  ntimes = args(2).idx_type_value ();
1216 
1217  if (ntimes < args(2).double_value ())
1218  error ("%s: REPEAT = %g is too large",
1219  who.c_str (), args(2).double_value ());
1220 
1221  nskip++;
1222  }
1223  }
1224 
1225  octave_value_list options = args.splice (0, nskip);
1226 
1227  octave_idx_type count = 0;
1228 
1229  octave_value result = os.textscan (fmt, ntimes, options, who, count);
1230 
1231  std::string errmsg = os.error ();
1232 
1233  return ovl (result, count, errmsg);
1234 }
1235 
1236 DEFMETHOD (textscan, interp, args, ,
1237  doc: /* -*- texinfo -*-
1238 @deftypefn {} {@var{C} =} textscan (@var{fid}, @var{format})
1239 @deftypefnx {} {@var{C} =} textscan (@var{fid}, @var{format}, @var{repeat})
1240 @deftypefnx {} {@var{C} =} textscan (@var{fid}, @var{format}, @var{param}, @var{value}, @dots{})
1241 @deftypefnx {} {@var{C} =} textscan (@var{fid}, @var{format}, @var{repeat}, @var{param}, @var{value}, @dots{})
1242 @deftypefnx {} {@var{C} =} textscan (@var{str}, @dots{})
1243 @deftypefnx {} {[@var{C}, @var{position}, @var{errmsg}] =} textscan (@dots{})
1244 Read data from a text file or string.
1245 
1246 The string @var{str} or file associated with @var{fid} is read from and
1247 parsed according to @var{format}. The function is an extension of
1248 @code{strread} and @code{textread}. Differences include: the ability to
1249 read from either a file or a string, additional options, and additional
1250 format specifiers.
1251 
1252 The input is interpreted as a sequence of words, delimiters (such as
1253 whitespace), and literals. The characters that form delimiters and
1254 whitespace are determined by the options. The format consists of format
1255 specifiers interspersed between literals. In the format, whitespace forms
1256 a delimiter between consecutive literals, but is otherwise ignored.
1257 
1258 The output @var{C} is a cell array where the number of columns is determined
1259 by the number of format specifiers.
1260 
1261 The first word of the input is matched to the first specifier of the format
1262 and placed in the first column of the output; the second is matched to the
1263 second specifier and placed in the second column and so forth. If there
1264 are more words than specifiers then the process is repeated until all words
1265 have been processed or the limit imposed by @var{repeat} has been met (see
1266 below).
1267 
1268 The string @var{format} describes how the words in @var{str} should be
1269 parsed. As in @var{fscanf}, any (non-whitespace) text in the format that is
1270 not one of these specifiers is considered a literal. If there is a literal
1271 between two format specifiers then that same literal must appear in the
1272 input stream between the matching words.
1273 
1274 The following specifiers are valid:
1275 
1276 @table @code
1277 @item %f
1278 @itemx %f64
1279 @itemx %n
1280 The word is parsed as a number and converted to double.
1281 
1282 @item %f32
1283 The word is parsed as a number and converted to single (float).
1284 
1285 @item %d
1286 @itemx %d8
1287 @itemx %d16
1288 @itemx %d32
1289 @itemx %d64
1290 The word is parsed as a number and converted to int8, int16, int32, or
1291 int64. If no size is specified then int32 is used.
1292 
1293 @item %u
1294 @itemx %u8
1295 @itemx %u16
1296 @itemx %u32
1297 @itemx %u64
1298 The word is parsed as a number and converted to uint8, uint16, uint32, or
1299 uint64. If no size is specified then uint32 is used.
1300 
1301 @item %s
1302 The word is parsed as a string ending at the last character before
1303 whitespace, an end-of-line, or a delimiter specified in the options.
1304 
1305 @item %q
1306 The word is parsed as a "quoted string".
1307 If the first character of the string is a double quote (") then the string
1308 includes everything until a matching double quote---including whitespace,
1309 delimiters, and end-of-line characters. If a pair of consecutive double
1310 quotes appears in the input, it is replaced in the output by a single
1311 double quote. For examples, the input "He said ""Hello""" would
1312 return the value 'He said "Hello"'.
1313 
1314 @item %c
1315 The next character of the input is read.
1316 This includes delimiters, whitespace, and end-of-line characters.
1317 
1318 @item %[@dots{}]
1319 @itemx %[^@dots{}]
1320 In the first form, the word consists of the longest run consisting of only
1321 characters between the brackets. Ranges of characters can be specified by
1322 a hyphen; for example, %[0-9a-zA-Z] matches all alphanumeric characters (if
1323 the underlying character set is ASCII). Since @sc{matlab} treats hyphens
1324 literally, this expansion only applies to alphanumeric characters. To
1325 include '-' in the set, it should appear first or last in the brackets; to
1326 include ']', it should be the first character. If the first character is
1327 '^' then the word consists of characters @strong{not} listed.
1328 
1329 @item %N@dots{}
1330 For %s, %c %d, %f, %n, %u, an optional width can be specified as %Ns, etc.
1331 where N is an integer > 1. For %c, this causes exactly N characters to be
1332 read instead of a single character. For the other specifiers, it is an
1333 upper bound on the number of characters read; normal delimiters can cause
1334 fewer characters to be read. For complex numbers, this limit applies to
1335 the real and imaginary components individually. For %f and %n, format
1336 specifiers like %N.Mf are allowed, where M is an upper bound on number of
1337 characters after the decimal point to be considered; subsequent digits are
1338 skipped. For example, the specifier %8.2f would read 12.345e6 as 1.234e7.
1339 
1340 @item %*@dots{}
1341 The word specified by the remainder of the conversion specifier is skipped.
1342 
1343 @item literals
1344 In addition the format may contain literal character strings; these will be
1345 skipped during reading. If the input string does not match this literal,
1346 the processing terminates.
1347 @end table
1348 
1349 Parsed words corresponding to the first specifier are returned in the first
1350 output argument and likewise for the rest of the specifiers.
1351 
1352 By default, if there is only one input argument, @var{format} is @t{"%f"}.
1353 This means that numbers are read from the input into a single column vector.
1354 If @var{format} is explicitly empty (@qcode{""}) then textscan will
1355 return data in a number of columns matching the number of fields on the
1356 first data line of the input. Either of these is suitable only when the
1357 input is exclusively numeric.
1358 
1359 For example, the string
1360 
1361 @smallexample
1362 @group
1363 @var{str} = "\
1364 Bunny Bugs 5.5\n\
1365 Duck Daffy -7.5e-5\n\
1366 Penguin Tux 6"
1367 @end group
1368 @end smallexample
1369 
1370 @noindent
1371 can be read using
1372 
1373 @example
1374 @var{a} = textscan (@var{str}, "%s %s %f");
1375 @end example
1376 
1377 The optional numeric argument @var{repeat} can be used for limiting the
1378 number of items read:
1379 
1380 @table @asis
1381 @item -1
1382 Read all of the string or file until the end (default).
1383 
1384 @item N
1385 Read until the first of two conditions occurs: 1) the format has been
1386 processed N times, or 2) N lines of the input have been processed. Zero
1387 (0) is an acceptable value for @var{repeat}. Currently, end-of-line
1388 characters inside %q, %c, and %[@dots{}]$ conversions do not contribute to
1389 the line count. This is incompatible with @sc{matlab} and may change in
1390 future.
1391 @end table
1392 
1393 The behavior of @code{textscan} can be changed via property/value pairs.
1394 The following properties are recognized:
1395 
1396 @table @asis
1397 @item @qcode{"BufSize"}
1398 This specifies the number of bytes to use for the internal buffer.
1399 A modest speed improvement may be obtained by setting this to a large value
1400 when reading a large file, especially if the input contains long strings.
1401 The default is 4096, or a value dependent on @var{n} if that is specified.
1402 
1403 @item @qcode{"CollectOutput"}
1404 A value of 1 or true instructs @code{textscan} to concatenate consecutive
1405 columns of the same class in the output cell array. A value of 0 or false
1406 (default) leaves output in distinct columns.
1407 
1408 @item @qcode{"CommentStyle"}
1409 Specify parts of the input which are considered comments and will be
1410 skipped. @var{value} is the comment style and can be either (1) A string
1411 or 1x1 cell string, to skip everything to the right of it; (2) A cell array
1412 of two strings, to skip everything between the first and second strings.
1413 Comments are only parsed where whitespace is accepted and do not act as
1414 delimiters.
1415 
1416 @item @qcode{"Delimiter"}
1417 If @var{value} is a string, any character in @var{value} will be used to
1418 split the input into words. If @var{value} is a cell array of strings,
1419 any string in the array will be used to split the input into words.
1420 (default value = any whitespace.)
1421 
1422 @item @qcode{"EmptyValue"}
1423 Value to return for empty numeric values in non-whitespace delimited data.
1424 The default is NaN@. When the data type does not support NaN (int32 for
1425 example), then the default is zero.
1426 
1427 @item @qcode{"EndOfLine"}
1428 @var{value} can be either an emtpy or one character specifying the
1429 end-of-line character, or the pair
1430 @qcode{"@xbackslashchar{}r@xbackslashchar{}n"} (CRLF).
1431 In the latter case, any of
1432 @qcode{"@xbackslashchar{}r"}, @qcode{"@xbackslashchar{}n"} or
1433 @qcode{"@xbackslashchar{}r@xbackslashchar{}n"} is counted as a (single)
1434 newline. If no value is given,
1435 @qcode{"@xbackslashchar{}r@xbackslashchar{}n"} is used.
1436 @c If set to "" (empty string) EOLs are ignored as delimiters and added
1437 @c to whitespace.
1438 
1439 @c When reading from a character string, optional input argument @var{n}
1440 @c specifies the number of times @var{format} should be used (i.e., to limit
1441 @c the amount of data read).
1442 @c When reading from file, @var{n} specifies the number of data lines to read;
1443 @c in this sense it differs slightly from the format repeat count in strread.
1444 
1445 @item @qcode{"HeaderLines"}
1446 The first @var{value} number of lines of @var{fid} are skipped. Note that
1447 this does not refer to the first non-comment lines, but the first lines of
1448 any type.
1449 
1450 @item @qcode{"MultipleDelimsAsOne"}
1451 If @var{value} is nonzero, treat a series of consecutive delimiters,
1452 without whitespace in between, as a single delimiter. Consecutive
1453 delimiter series need not be vertically aligned. Without this option, a
1454 single delimiter before the end of the line does not cause the line to be
1455 considered to end with an empty value, but a single delimiter at the start
1456 of a line causes the line to be considered to start with an empty value.
1457 
1458 @item @qcode{"TreatAsEmpty"}
1459 Treat single occurrences (surrounded by delimiters or whitespace) of the
1460 string(s) in @var{value} as missing values.
1461 
1462 @item @qcode{"ReturnOnError"}
1463 If set to numerical 1 or true, return normally as soon as an error is
1464 encountered, such as trying to read a string using @code{%f}.
1465 If set to 0 or false, return an error and no data.
1466 
1467 @item @qcode{"Whitespace"}
1468 Any character in @var{value} will be interpreted as whitespace and trimmed;
1469 The default value for whitespace is
1470 @c Note: the next line specifically has a newline which generates a space
1471 @c in the output of qcode, but keeps the next line < 80 characters.
1472 @qcode{"
1473 @xbackslashchar{}b@xbackslashchar{}r@xbackslashchar{}n@xbackslashchar{}t"}
1474 (note the space). Unless whitespace is set to @qcode{""} (empty) AND at
1475 least one @qcode{"%s"} format conversion specifier is supplied, a space is
1476 always part of whitespace.
1477 
1478 @end table
1479 
1480 When the number of words in @var{str} or @var{fid} doesn't match an exact
1481 multiple of the number of format conversion specifiers, @code{textscan}'s
1482 behavior depends on whether the last character of the string or file is an
1483 end-of-line as specified by the @code{EndOfLine} option:
1484 
1485 @table @asis
1486 @item last character = end-of-line
1487 Data columns are padded with empty fields, NaN or 0 (for integer fields) so
1488 that all columns have equal length
1489 
1490 @item last character is not end-of-line
1491 Data columns are not padded; @code{textscan} returns columns of unequal
1492 length
1493 @end table
1494 
1495 The second output @var{position} provides the location, in characters
1496 from the beginning of the file or string, where processing stopped.
1497 
1498 @seealso{dlmread, fscanf, load, strread, textread}
1499 @end deftypefn */)
1500 {
1501  static std::string who = "textscan";
1502 
1503  return textscan_internal (interp, who, args);
1504 }
1505 
1506 DEFMETHOD (__textscan__, interp, args, ,
1507  doc: /* -*- texinfo -*-
1508 @deftypefn {} {@var{C} =} __textscan__ (@var{who}, @dots{})
1509 Like @code{textscan} but accept additional argument @var{who} to use
1510 as the name of the function when reporting errors.
1511 @end deftypefn */)
1512 {
1513  if (args.length () == 0)
1514  print_usage ();
1515 
1516  return textscan_internal (interp, args(0).string_value (),
1517  args.splice (0, 1));
1518 }
1519 
1520 /*
1521 %!test
1522 %! str = "1, 2, 3, 4\n 5, , , 8\n 9, 10, 11, 12";
1523 %! fmtstr = "%f %d %f %s";
1524 %! c = textscan (str, fmtstr, 2, "delimiter", ",", "emptyvalue", -Inf);
1525 %! assert (c{1}, [1;5]);
1526 %! assert (c{3}, [3; -Inf]);
1527 %! assert (iscellstr (c{4}));
1528 
1529 %!test
1530 %! b = [10:10:100];
1531 %! b = [b; 8*b/5];
1532 %! str = sprintf ("%g miles/hr = %g kilometers/hr\n", b);
1533 %! fmt = "%f miles/hr = %f kilometers/hr";
1534 %! c = textscan (str, fmt);
1535 %! assert (c{1}, b(1,:)', 1e-5);
1536 %! assert (c{2}, b(2,:)', 1e-5);
1537 
1538 %!test
1539 %! str = "13, -, NA, str1, -25\r\n// Middle line\r\n36, na, 05, str3, 6";
1540 %! c = textscan (str, "%d %n %f %s %n", "delimiter", ",",
1541 %! "treatAsEmpty", {"NA", "na", "-"}, "commentStyle", "//");
1542 %! assert (c{1}, int32 ([13; 36]));
1543 %! assert (c{2}, [NaN; NaN]);
1544 %! assert (c{3}, [NaN; 5]);
1545 %! assert (c{4}, {"str1"; "str3"});
1546 %! assert (c{5}, [-25; 6]);
1547 
1548 %!test
1549 %! str = "Km:10 = hhhBjjj miles16hour\r\n";
1550 %! str = [str "Km:15 = hhhJjjj miles241hour\r\n"];
1551 %! str = [str "Km:2 = hhhRjjj miles3hour\r\n"];
1552 %! str = [str "Km:25 = hhhZ\r\n"];
1553 %! fmt = "Km:%d = hhh%1sjjj miles%dhour";
1554 %! c = textscan (str, fmt, "delimiter", " ");
1555 %! assert (c{1}', int32 ([10, 15, 2, 25]));
1556 %! assert (c{2}', {'B' 'J' 'R' 'Z'});
1557 %! assert (c{3}', int32 ([16, 241, 3, 0]));
1558 
1559 ## Test with default EndOfLine parameter
1560 %!test
1561 %! c = textscan ("L1\nL2", "%s");
1562 %! assert (c{:}, {"L1"; "L2"});
1563 
1564 ## Test with EndofLine parameter set to "" (empty) - newline should be in word
1565 %!test
1566 %! c = textscan ("L1\nL2", "%s", "endofline", "");
1567 %! assert (int8 ([c{:}{:}]), int8 ([76, 49, 10, 76, 50]));
1568 
1569 ## Matlab fails this test. A literal after a conversion is not a delimiter
1570 %!#test
1571 %! ## No delimiters at all besides EOL. Skip fields, even empty fields
1572 %! str = "Text1Text2Text\nTextText4Text\nText57Text";
1573 %! c = textscan (str, "Text%*dText%dText");
1574 %! assert (c{1}, int32 ([2; 4; 0]));
1575 
1576 ## CollectOutput test
1577 %!test
1578 %! b = [10:10:100];
1579 %! b = [b; 8*b/5; 8*b*1000/5];
1580 %! str = sprintf ("%g miles/hr = %g (%g) kilometers (meters)/hr\n", b);
1581 %! fmt = "%f miles%s %s %f (%f) kilometers %*s";
1582 %! c = textscan (str, fmt, "collectoutput", 1);
1583 %! assert (size (c{3}), [10, 2]);
1584 %! assert (size (c{2}), [10, 2]);
1585 
1586 ## CollectOutput test with uneven column length files
1587 %!test
1588 %! b = [10:10:100];
1589 %! b = [b; 8*b/5; 8*b*1000/5];
1590 %! str = sprintf ("%g miles/hr = %g (%g) kilometers (meters)/hr\n", b);
1591 %! str = [str "110 miles/hr"];
1592 %! fmt = "%f miles%s %s %f (%f) kilometers %*s";
1593 %! c = textscan (str, fmt, "collectoutput", 1);
1594 %! assert (size (c{1}), [11, 1]);
1595 %! assert (size (c{3}), [11, 2]);
1596 %! assert (size (c{2}), [11, 2]);
1597 %! assert (c{3}(end), NaN);
1598 %! assert (c{2}{11, 1}, "/hr");
1599 %! assert (isempty (c{2}{11, 2}), true);
1600 
1601 ## Double quoted string
1602 %!test
1603 %! str = 'First "the second called ""the middle""" third';
1604 %! fmt = "%q";
1605 %! c = textscan (str, fmt);
1606 %! assert (c{1}, {"First"; 'the second called "the middle"'; "third"});
1607 
1608 ## Arbitrary character
1609 %!test
1610 %! c = textscan ("a first, \n second, third", "%s %c %11c", "delimiter", " ,");
1611 %! assert (c{1}, {"a"; "ond"});
1612 %! assert (c{2}, {"f"; "t"});
1613 %! assert (c{3}, {"irst, \n sec"; "hird"});
1614 
1615 ## Field width and non-standard delimiters
1616 %!test
1617 %! str = "12;34;123456789;7";
1618 %! c = textscan (str, "%4d %4d", "delimiter", ";", "collectOutput", 1);
1619 %! assert (c, {[12, 34; 1234, 5678; 9, 7]});
1620 
1621 ## Field width and non-standard delimiters (2)
1622 %!test
1623 %! str = "12;34;123456789;7";
1624 %! c = textscan (str, "%4f %f", "delimiter", ";", "collectOutput", 1);
1625 %! assert (c, {[12, 34; 1234, 56789; 7, NaN]});
1626 
1627 ## Ignore trailing delimiter, but use leading one
1628 %!test
1629 %! str = "12.234e+2,34, \n12345.789-9876j,78\n,10|3";
1630 %! c = textscan (str, "%10.2f %f", "delimiter", ",", "collectOutput", 1,
1631 %! "expChars", "e|");
1632 %! assert (c, {[1223, 34; 12345.79-9876j, 78; NaN, 10000]}, 1e-6);
1633 
1634 ## Multi-character delimiter
1635 %!test
1636 %! str = "99end2 space88gap 4564";
1637 %! c = textscan (str, "%d %s", "delimiter", {"end", "gap", "space"});
1638 %! assert (c{1}, int32 ([99; 88]));
1639 %! assert (c{2}, {"2 "; "4564"});
1640 
1641 ## FIXME: Following two tests still fail (4/13/2016).
1642 ## Delimiters as part of literals, and following literals
1643 %!#test
1644 %! str = "12 R&D & 7";
1645 %! c = textscan (str, "%f R&D %f", "delimiter", "&", "collectOutput", 1,
1646 %! "EmptyValue", -99);
1647 %! assert (c, {[12, -99; 7, -99]});
1648 
1649 ## Delimiters as part of literals, and before literals
1650 %!#test
1651 %! str = "12 & R&D 7";
1652 %! c = textscan (str, "%f R&D %f", "delimiter", "&", "collectOutput", 1);
1653 %! assert (c, {[12 7]});
1654 
1655 ## Check number of lines read, not number of passes through format string
1656 %!test
1657 %! f = tempname ();
1658 %! fid = fopen (f, "w+");
1659 %! fprintf (fid, "1\n2\n3\n4\n5\n6");
1660 %! fseek (fid, 0, "bof");
1661 %! c = textscan (fid, "%f %f", 2);
1662 %! E = feof (fid);
1663 %! fclose (fid);
1664 %! unlink (f);
1665 %! assert (c, {1, 2});
1666 %! assert (! E);
1667 
1668 ## Check number of lines read, not number of passes through format string
1669 %!test
1670 %! f = tempname ();
1671 %! fid = fopen (f, "w+");
1672 %! fprintf (fid, "1\r\n2\r3\n4\r\n5\n6");
1673 %! fseek (fid, 0, "bof");
1674 %! c = textscan (fid, "%f %f", 4);
1675 %! fclose (fid);
1676 %! unlink (f);
1677 %! assert (c, {[1;3], [2;4]});
1678 
1679 ## Check number of lines read, with multiple delimiters
1680 %!test
1681 %! f = tempname ();
1682 %! fid = fopen (f, "w+");
1683 %! fprintf (fid, "1-\r\n-2\r3-\n-4\r\n5\n6");
1684 %! fseek (fid, 0, "bof");
1685 %! c = textscan (fid, "%f %f", 4, "delimiter", "-", "multipleDelimsAsOne", 1);
1686 %! fclose (fid);
1687 %! unlink (f);
1688 %! assert (c, {[1;3], [2;4]});
1689 
1690 ## Check ReturnOnError
1691 %!test
1692 %! f = tempname ();
1693 %! fid = fopen (f, "w+");
1694 %! str = "1 2 3\n4 s 6";
1695 %! fprintf (fid, str);
1696 %! fseek (fid, 0, "bof");
1697 %! c = textscan (fid, "%f %f %f", "ReturnOnError", 1);
1698 %! fseek (fid, 0, "bof");
1699 %! fclose (fid);
1700 %! unlink (f);
1701 %! u = textscan (str, "%f %f %f", "ReturnOnError", 1);
1702 %! assert (c, {[1;4], [2], [3]});
1703 %! assert (u, {[1;4], [2], [3]});
1704 
1705 %! ## Check ReturnOnError (2)
1706 %!test
1707 %! f = tempname ();
1708 %! fid = fopen (f, "w+");
1709 %! str = "1 2 3\n4 s 6\n";
1710 %! fprintf (fid, str);
1711 %! fseek (fid, 0, "bof");
1712 %! c = textscan (fid, "%f %f %f", "ReturnOnError", 1);
1713 %! fseek (fid, 0, "bof");
1714 %! fclose (fid);
1715 %! unlink (f);
1716 %! u = textscan (str, "%f %f %f", "ReturnOnError", 1);
1717 %! assert (c, {[1;4], 2, 3});
1718 %! assert (u, {[1;4], 2, 3});
1719 
1720 %!error <Read error in field 2 of row 2>
1721 %! textscan ("1 2 3\n4 s 6", "%f %f %f", "ReturnOnError", 0);
1722 
1723 ## Check ReturnOnError (3)
1724 %!test
1725 %! f = tempname ();
1726 %! fid = fopen (f, "w+");
1727 %! fprintf (fid, "1 s 3\n4 5 6");
1728 %! fseek (fid, 0, "bof");
1729 %! c = textscan (fid, "", "ReturnOnError", 1);
1730 %! fseek (fid, 0, "bof");
1731 %! fclose (fid);
1732 %! unlink (f);
1733 %! assert (c, {1});
1734 
1735 ## Check ReturnOnError with empty fields
1736 %!test
1737 %! c = textscan ("1,,3\n4,5,6", "", "Delimiter", ",", "ReturnOnError", 1);
1738 %! assert (c, {[1;4], [NaN;5], [3;6]});
1739 
1740 ## Check ReturnOnError with empty fields (2)
1741 %!test
1742 %! c = textscan ("1,,3\n4,5,6", "%f %f %f", "Delimiter", ",",
1743 %! "ReturnOnError", 1);
1744 %! assert (c, {[1;4], [NaN;5], [3;6]});
1745 
1746 ## Check ReturnOnError in first column
1747 %!test
1748 %! c = textscan ("1 2 3\ns 5 6", "", "ReturnOnError", 1);
1749 %! assert (c, {1, 2, 3});
1750 
1751 ## FIXME: This test fails (4/14/16)
1752 ## Test incomplete first data line
1753 %!#test
1754 %! R = textscan (['Empty1' char(10)], 'Empty%d %f');
1755 %! assert (R{1}, int32 (1));
1756 %! assert (isempty (R{2}), true);
1757 
1758 %!test <*37023>
1759 %! data = textscan (" 1. 1 \n 2 3\n", '%f %f');
1760 %! assert (data{1}, [1; 2], 1e-15);
1761 %! assert (data{2}, [1; 3], 1e-15);
1762 
1763 ## Whitespace test using delimiter ";"
1764 %!test <*37333>
1765 %! tc{1, 1} = "C:/code;";
1766 %! tc{1, end+1} = "C:/code/meas;";
1767 %! tc{1, end+1} = " C:/code/sim;";
1768 %! tc{1, end+1} = "C:/code/utils;";
1769 %! string = [tc{:}];
1770 %! c = textscan (string, "%s", "delimiter", ";");
1771 %! for k = 1:max (numel (c{1}), numel (tc))
1772 %! lh = c{1}{k};
1773 %! rh = tc{k};
1774 %! rh(rh == ";") = "";
1775 %! rh = strtrim (rh);
1776 %! assert (strcmp (lh, rh));
1777 %! endfor
1778 
1779 ## Whitespace test, adding multipleDelimsAsOne true arg
1780 %!test <*37333>
1781 %! tc{1, 1} = "C:/code;";
1782 %! tc{1, end+1} = " C:/code/meas;";
1783 %! tc{1, end+1} = "C:/code/sim;;";
1784 %! tc{1, end+1} = "C:/code/utils;";
1785 %! string = [tc{:}];
1786 %! c = textscan (string, "%s", "delimiter", ";", "multipleDelimsAsOne", 1);
1787 %! for k = 1:max (numel (c{1}), numel (tc))
1788 %! lh = c{1}{k};
1789 %! rh = tc{k};
1790 %! rh(rh == ";") = "";
1791 %! rh = strtrim (rh);
1792 %! assert (strcmp (lh, rh));
1793 %! endfor
1794 
1795 ## Whitespace test (bug #37333), adding multipleDelimsAsOne false arg
1796 %!test <*37333>
1797 %! tc{1, 1} = "C:/code;";
1798 %! tc{1, end+1} = " C:/code/meas;";
1799 %! tc{1, end+1} = "C:/code/sim;;";
1800 %! tc{1, end+1} = "";
1801 %! tc{1, end+1} = "C:/code/utils;";
1802 %! string = [tc{:}];
1803 %! c = textscan (string, "%s", "delimiter", ";", "multipleDelimsAsOne", 0);
1804 %! for k = 1:max (numel (c{1}), numel (tc))
1805 %! lh = c{1}{k};
1806 %! rh = tc{k};
1807 %! rh(rh == ";") = "";
1808 %! rh = strtrim (rh);
1809 %! assert (strcmp (lh, rh));
1810 %! endfor
1811 
1812 ## Whitespace test (bug #37333) whitespace "" arg
1813 %!test <*37333>
1814 %! tc{1, 1} = "C:/code;";
1815 %! tc{1, end+1} = " C:/code/meas;";
1816 %! tc{1, end+1} = "C:/code/sim;";
1817 %! tc{1, end+1} = "C:/code/utils;";
1818 %! string = [tc{:}];
1819 %! c = textscan (string, "%s", "delimiter", ";", "whitespace", "");
1820 %! for k = 1:max (numel (c{1}), numel (tc))
1821 %! lh = c{1}{k};
1822 %! rh = tc{k};
1823 %! rh(rh == ";") = "";
1824 %! assert (strcmp (lh, rh));
1825 %! endfor
1826 
1827 ## Whitespace test (bug #37333), whitespace " " arg
1828 %!test <*37333>
1829 %! tc{1, 1} = "C:/code;";
1830 %! tc{1, end+1} = " C:/code/meas;";
1831 %! tc{1, end+1} = "C:/code/sim;";
1832 %! tc{1, end+1} = "C:/code/utils;";
1833 %! string = [tc{:}];
1834 %! c = textscan (string, "%s", "delimiter", ";", "whitespace", " ");
1835 %! for k = 1:max (numel (c{1}), numel (tc))
1836 %! lh = c{1}{k};
1837 %! rh = tc{k};
1838 %! rh(rh == ";") = "";
1839 %! rh = strtrim (rh);
1840 %! assert (strcmp (lh, rh));
1841 %! endfor
1842 
1843 ## Tests reading with empty format, should return proper nr of columns
1844 %!test
1845 %! f = tempname ();
1846 %! fid = fopen (f, "w+");
1847 %! fprintf (fid, " 1 2 3 4\n5 6 7 8");
1848 %! fseek (fid, 0, "bof");
1849 %! C = textscan (fid, "");
1850 %! E = feof (fid);
1851 %! fclose (fid);
1852 %! unlink (f);
1853 %! assert (C{1}, [1 ; 5], 1e-6);
1854 %! assert (C{2}, [2 ; 6], 1e-6);
1855 %! assert (C{3}, [3 ; 7], 1e-6);
1856 %! assert (C{4}, [4 ; 8], 1e-6);
1857 %! assert (E);
1858 
1859 ## Test leaving the file at the correct position on exit
1860 %!test
1861 %! f = tempname ();
1862 %! fid = fopen (f, "w+");
1863 %! fprintf (fid, "1,2\n3,4\n");
1864 %! fseek (fid, 0, "bof");
1865 %! C = textscan (fid, "%s %f", 2, "Delimiter", ",");
1866 %! E = ftell (fid);
1867 %! fclose (fid);
1868 %! unlink (f);
1869 %! assert (E, 8);
1870 
1871 ## Tests reading with empty format; empty fields & incomplete lower row
1872 %!test
1873 %! f = tempname ();
1874 %! fid = fopen (f, "w+");
1875 %! fprintf (fid, " ,2,,4\n5,6");
1876 %! fseek (fid, 0, "bof");
1877 %! C = textscan (fid, "", "delimiter", ",", "EmptyValue", 999,
1878 %! "CollectOutput" , 1);
1879 %! fclose (fid);
1880 %! unlink (f);
1881 %! assert (C{1}, [999, 2, 999, 4; 5, 6, 999, 999], 1e-6);
1882 
1883 ## Error message tests
1884 
1885 %!test
1886 %! f = tempname ();
1887 %! fid = fopen (f, "w+");
1888 %! msg1 = "textscan: 1 parameters given, but only 0 values";
1889 %! try
1890 %! C = textscan (fid, "", "headerlines");
1891 %! end_try_catch;
1892 %! assert (! feof (fid));
1893 %! fclose (fid);
1894 %! unlink (f);
1895 %! assert (msg1, lasterr);
1896 
1897 %!test
1898 %! f = tempname ();
1899 %! fid = fopen (f, "w+");
1900 %! msg1 = "textscan: HeaderLines must be numeric";
1901 %! try
1902 %! C = textscan (fid, "", "headerlines", "hh");
1903 %! end_try_catch;
1904 %! fclose (fid);
1905 %! unlink (f);
1906 %! assert (msg1, lasterr);
1907 
1908 ## Skip headerlines
1909 %!test
1910 %! C = textscan ("field 1 field2\n 1 2\n3 4", "", "headerlines", 1,
1911 %! "collectOutput", 1);
1912 %! assert (C, {[1 2; 3 4]});
1913 
1914 ## Skip headerlines with non-default EOL
1915 %!test
1916 %! C = textscan ("field 1 field2\r 1 2\r3 4", "", "headerlines", 2,
1917 %! "collectOutput", 1, "EndOfLine", '\r');
1918 %! assert (C, {[3 4]});
1919 
1920 %!test
1921 %! f = tempname ();
1922 %! fid = fopen (f, "w+");
1923 %! fprintf (fid,"some_string");
1924 %! fseek (fid, 0, "bof");
1925 %! msg1 = "textscan: EndOfLine must be at most one character or '\\r\\n'";
1926 %! try
1927 %! C = textscan (fid, "%f", "EndOfLine", "\n\r");
1928 %! end_try_catch;
1929 %! fclose (fid);
1930 %! unlink (f);
1931 %! assert (msg1, lasterr);
1932 
1933 %!test
1934 %! f = tempname ();
1935 %! fid = fopen (f, "w+");
1936 %! fprintf (fid,"some_string");
1937 %! fseek (fid, 0, "bof");
1938 %! msg1 = "textscan: EndOfLine must be at most one character or '\\r\\n'";
1939 %! try
1940 %! C = textscan (fid, "%f", "EndOfLine", 33);
1941 %! end_try_catch;
1942 %! fclose (fid);
1943 %! unlink (f);
1944 %! assert (msg1, lasterr);
1945 
1946 %!assert <*41824> (textscan ("123", "", "whitespace", " "){:}, 123);
1947 
1948 ## just test supplied emptyvalue
1949 %!assert <*42343> (textscan (",NaN", "", "delimiter", "," ,"emptyValue" ,Inf),
1950 %! {Inf, NaN})
1951 
1952 ## test padding with supplied emptyvalue
1953 %!test <*42343>
1954 %! c = textscan (",1,,4\nInf, ,NaN\n", "", "delimiter", ",",
1955 %! "emptyvalue", -10);
1956 %! assert (cell2mat (c), [-10, 1, -10, 4; Inf, -10, NaN, -10]);
1957 
1958 %!test <*42528>
1959 %! assert (textscan ("1i", ""){1}, 0+1i);
1960 %! C = textscan ("3, 2-4i, NaN\n -i, 1, 23.4+2.2i\n 1+1 1+1j", "",
1961 %! "delimiter", ",");
1962 %! assert (cell2mat (C), [3+0i, 2-4i, NaN+0i; 0-i, 1+0i, 23.4+2.2i; 1 1 1+1i]);
1963 
1964 %!test
1965 %! ## TreatAsEmpty
1966 %! C = textscan ("1,2,3,NN,5,6\n", "%d%d%d%f", "delimiter", ",",
1967 %! "TreatAsEmpty", "NN");
1968 %! assert (C{3}(1), int32 (3));
1969 %! assert (C{4}(1), NaN);
1970 
1971 ## MultipleDelimsAsOne
1972 %!test
1973 %! str = "11, 12, 13,, 15\n21,, 23, 24, 25\n,, 33, 34, 35\n";
1974 %! C = textscan (str, "%f %f %f %f", "delimiter", ",",
1975 %! "multipledelimsasone", 1, "endofline", "\n");
1976 %! assert (C{1}', [11, 21, 33]);
1977 %! assert (C{2}', [12, 23, 34]);
1978 %! assert (C{3}', [13, 24, 35]);
1979 %! assert (C{4}', [15, 25, NaN]);
1980 
1981 ## Single-quoted escape sequences
1982 %!test
1983 %! str = "11\t12\t13\r21\t22\t23";
1984 %! c = textscan (str, "", "delimiter", '\t', "EndOfLine", '\r');
1985 %! assert (c{1}', [11, 21]);
1986 %! assert (c{2}', [12, 22]);
1987 %! assert (c{3}', [13, 23]);
1988 
1989 %!test <*44750>
1990 %! c = textscan ("/home/foo/", "%s", "delimiter", "/",
1991 %! "MultipleDelimsAsOne", 1);
1992 %! assert (c{1}, {"home"; "foo"});
1993 
1994 ## FIXME: Test still fails (4/13/2016).
1995 ## Allow cuddling %sliteral, but warn it is ambiguous
1996 %!#test
1997 %! C = textscan ("abcxyz51\nxyz83\n##xyz101", "%s xyz %d");
1998 %! assert (C{1}([1 3]), {"abc"; "##"});
1999 %! assert (isempty (C{1}{2}), true);
2000 %! assert (C{2}, int32 ([51; 83; 101]));
2001 
2002 ## Literals are not delimiters.
2003 
2004 ## Test for false positives in check for non-supported format specifiers
2005 %!test
2006 %! c = textscan ("Total: 32.5 % (of cm values)",
2007 %! "Total: %f %% (of cm values)");
2008 %! assert (c{1}, 32.5, 1e-5);
2009 
2010 ## Test various forms of string format specifiers
2011 %!test <*45712>
2012 %! str = "14 :1 z:2 z:3 z:5 z:11";
2013 %! C = textscan (str, "%f %s %*s %3s %*3s %f", "delimiter", ":");
2014 %! assert (C, {14, {"1 z"}, {"3 z"}, 11});
2015 
2016 ## Bit width, fixed width conversion specifiers
2017 %!test
2018 %! str2 = "123456789012345 ";
2019 %! str2 = [str2 str2 str2 str2 str2 str2 str2 str2];
2020 %! str2 = [str2 "123456789.01234 1234567890.1234 12345.678901234 12345.678901234"];
2021 %! pttrn = "%3u8%*s %5u16%*s %10u32%*s %15u64 %3d8%*s %5d16%*s %10d32%*s %15d64 %9f32%*s %14f64%*s %10.2f32%*s %12.2f64%*s";
2022 %! C = textscan (str2, pttrn, "delimiter", " ");
2023 %! assert (C{1}, uint8 (123));
2024 %! assert (C{2}, uint16 (12345));
2025 %! assert (C{3}, uint32 (1234567890));
2026 %! assert (C{4}, uint64 (123456789012345));
2027 %! assert (C{5}, int8 (123));
2028 %! assert (C{6}, int16 (12345));
2029 %! assert (C{7}, int32 (1234567890));
2030 %! assert (C{8}, int64 (123456789012345));
2031 %! assert (C{9}, single (123456789), 1e-12);
2032 %! assert (C{10}, double (1234567890.123), 1e-15);
2033 %! assert (C{11}, single (12345.68), 1e-5);
2034 %! assert (C{12}, double (12345.68), 1e-11);
2035 
2036 ## Bit width, fixed width conv. specifiers -- check the right amount is left
2037 %!test
2038 %! str2 = "123456789012345 ";
2039 %! str2 = [str2 str2 "123456789.01234"];
2040 %! pttrn = "%3u8 %5u16 %10u32 %3d8 %5d16 %10d32 %9f32 %9f";
2041 %! C = textscan (str2, pttrn, "delimiter", " ");
2042 %! assert (C{1}, uint8 (123));
2043 %! assert (C{2}, uint16 (45678));
2044 %! assert (C{3}, uint32 (9012345));
2045 %! assert (C{4}, int8 (123));
2046 %! assert (C{5}, int16 (45678));
2047 %! assert (C{6}, int32 (9012345));
2048 %! assert (C{7}, single (123456789), 1e-12);
2049 %! assert (C{8}, double (0.01234), 1e-12);
2050 
2051 %!test
2052 %! C = textscan ("123.123", "%2f %3f %3f");
2053 %! assert (C{1}, 12);
2054 %! assert (C{2}, 3.1, 1e-11);
2055 %! assert (C{3}, 23);
2056 
2057 %!test
2058 %! C = textscan ("123.123", "%3f %3f %3f");
2059 %! assert (C{1}, 123);
2060 %! assert (C{2}, 0.12, 1e-11);
2061 %! assert (C{3}, 3);
2062 
2063 %!test
2064 %! C = textscan ("123.123", "%4f %3f");
2065 %! assert (C{1}, 123);
2066 %! assert (C{2}, 123);
2067 
2068 ## field width interrupts exponent. (Matlab incorrectly gives [12, 2e12])
2069 %!test
2070 %! assert (textscan ("12e12", "%4f"), {[120; 2]});
2071 %! assert (textscan ("12e+12", "%5f"), {[120; 2]});
2072 %! assert (textscan ("125e-12","%6f"), {[12.5; 2]});
2073 
2074 ## %[] tests
2075 ## Plain [..] and *[..]
2076 %!test
2077 %! ar = "abcdefguvwxAny\nacegxyzTrailing\nJunk";
2078 %! C = textscan (ar, "%[abcdefg] %*[uvwxyz] %s");
2079 %! assert (C{1}, {"abcdefg"; "aceg"; ""});
2080 %! assert (C{2}, {"Any"; "Trailing"; "Junk"});
2081 
2082 %!test
2083 %! assert (textscan ("A2 B2 C3", "%*[ABC]%d", 3), {int32([2; 2; 3])});
2084 
2085 ## [^..] and *[^..]
2086 %!test
2087 %! br = "abcdefguvwx1Any\nacegxyz2Trailing\n3Junk";
2088 %! C = textscan (br, "%[abcdefg] %*[^0123456789] %s");
2089 %! assert (C{1}, {"abcdefg"; "aceg"; ""});
2090 %! assert (C{2}, {"1Any"; "2Trailing"; "3Junk"});
2091 
2092 ## [..] and [^..] containing delimiters
2093 %!test
2094 %! cr = "ab cd efguv wx1Any\na ce gx yz2Trailing\n 3Junk";
2095 %! C = textscan (cr, "%[ abcdefg] %*[^0123456789] %s", "delimiter", " \n",
2096 %! "whitespace", "");
2097 %! assert (C{1}, {"ab cd efg"; "a ce g"; " "});
2098 %! assert (C{2}, {"1Any"; "2Trailing"; "3Junk"});
2099 
2100 %!assert <*36464> (textscan ("1 2 3 4 5 6", "%*n%n%*[^\n]"){1}, 2);
2101 
2102 ## test %[]] and %[^]]
2103 %!test
2104 %! assert (textscan ("345]", "%*[123456]%[]]"){1}{1}, "]");
2105 %! assert (textscan ("345]", "%*[^]]%s"){1}{1}, "]");
2106 
2107 ## Test that "-i" checks the next two characters
2108 %!test
2109 %! C = textscan ("-i -in -inf -infinity", "%f %f%s %f %f %s");
2110 %! assert (C, {-i, -i, {"n"}, -Inf, -Inf, {"inity"}});
2111 
2112 ## Again for "+i", this time with custom parser
2113 %!test
2114 %! C = textscan ("+i +in +inf +infinity", "%f %f%s %f %f %s", "ExpChars", "eE");
2115 %! assert (C, {i, i, {"n"}, Inf, Inf, {"inity"}});
2116 
2117 ## Check single quoted format interprets control sequences
2118 %!test
2119 %! C = textscan ("1 2\t3 4", '%f %[^\t] %f %f');
2120 %! assert (C, {1, {"2"}, 3, 4});
2121 
2122 ## Check a non-empty line with no valid conversion registers empytValue
2123 %!test
2124 %! C = textscan ("Empty\n", "Empty%f %f");
2125 %! assert (C, { NaN, NaN });
2126 
2127 ## Check overflow and underflow of integer types
2128 %!test
2129 %! a = "-1e90 ";
2130 %! b = "1e90 ";
2131 %! fmt = "%d8 %d16 %d32 %d64 %u8 %u16 %u32 %u64 ";
2132 %! C = textscan ([a a a a a a a a b b b b b b b b], fmt);
2133 %! assert (C{1}, int8 ([-128; 127]));
2134 %! assert (C{2}, int16 ([-32768; 32767]));
2135 %! assert (C{3}, int32 ([-2147483648; 2147483647]));
2136 %! assert (C{4}, int64 ([-9223372036854775808; 9223372036854775807]));
2137 %! assert (C{5}, uint8 ([0; 255]));
2138 %! assert (C{6}, uint16 ([0; 65535]));
2139 %! assert (C{7}, uint32 ([0; 4294967295]));
2140 %! assert (C{8}, uint64 ([0; 18446744073709551615]));
2141 
2142 ## Tests from Matlab (does The MathWorks have any copyright over the input?)
2143 %!test
2144 %! f = tempname ();
2145 %! fid = fopen (f, "w+");
2146 %! fprintf (fid,"09/12/2005 Level1 12.34 45 1.23e10 inf Nan Yes 5.1+3i\n");
2147 %! fprintf (fid,"10/12/2005 Level2 23.54 60 9e19 -inf 0.001 No 2.2-.5i\n");
2148 %! fprintf (fid,"11/12/2005 Level3 34.90 12 2e5 10 100 No 3.1+.1i\n");
2149 %! fseek (fid, 0, "bof");
2150 %! C = textscan (fid,"%s %s %f32 %d8 %u %f %f %s %f");
2151 %! %assert (C{1}, {"09/12/2005";"10/12/2005";"11/12/2005"});
2152 %! assert (C{2}, {"Level1";"Level2";"Level3"});
2153 %! assert (C{3}, [single(12.34);single(23.54);single(34.90)]);
2154 %! assert (C{4}, [int8(45);int8(60);int8(12)]);
2155 %! assert (C{5}, [uint32(4294967295);uint32(4294967295);uint32(200000)]);
2156 %! assert (C{6}, [inf;-inf;10]);
2157 %! assert (C{7}, [NaN;0.001;100], eps);
2158 %! assert (C{8}, {"Yes";"No";"No"});
2159 %! assert (C{9}, [5.1+3i;2.2-0.5i;3.1+0.1i]);
2160 %! fseek (fid, 0, "bof");
2161 %! C = textscan (fid,"%s Level%d %f32 %d8 %u %f %f %s %f");
2162 %! assert (C{2}, [int32(1);int32(2);int32(3)]);
2163 %! assert (C{3}, [single(12.34);single(23.54);single(34.90)]);
2164 %! fseek (fid, 0, "bof");
2165 %! C = textscan (fid, '%s %*[^\n]');
2166 %! fclose (fid);
2167 %! unlink (f);
2168 %! assert (C, {{"09/12/2005";"10/12/2005";"11/12/2005"}});
2169 
2170 %!test
2171 %! f = tempname ();
2172 %! fid = fopen (f, "w+");
2173 %! fprintf (fid,"1, 2, 3, 4, , 6\n");
2174 %! fprintf (fid,"7, 8, 9, , 11, 12\n");
2175 %! fseek (fid, 0, "bof");
2176 %! C = textscan (fid,"%f %f %f %f %u8 %f", "Delimiter",",","EmptyValue",-Inf);
2177 %! fclose (fid);
2178 %! unlink (f);
2179 %! assert (C{4}, [4; -Inf]);
2180 %! assert (C{5}, uint8 ([0; 11]));
2181 
2182 %!test
2183 %! f = tempname ();
2184 %! fid = fopen (f, "w+");
2185 %! fprintf (fid,"abc, 2, NA, 3, 4\n");
2186 %! fprintf (fid,"// Comment Here\n");
2187 %! fprintf (fid,"def, na, 5, 6, 7\n");
2188 %! fseek (fid, 0, "bof");
2189 %! C = textscan (fid, "%s %n %n %n %n", "Delimiter", ",",
2190 %! "TreatAsEmpty", {"NA","na"}, "CommentStyle", "//");
2191 %! fclose (fid);
2192 %! unlink (f);
2193 %! assert (C{1}, {"abc";"def"});
2194 %! assert (C{2}, [2; NaN]);
2195 %! assert (C{3}, [NaN; 5]);
2196 %! assert (C{4}, [3; 6]);
2197 %! assert (C{5}, [4; 7]);
2198 
2199 ## FIXME: Almost passes. Second return value is {"/"}. Tested 4/14/16.
2200 ## Test start of comment as string
2201 %!#test
2202 %! c = textscan ("1 / 2 // 3", "%n %s %u8", "CommentStyle", {"//"});
2203 %! assert (c(1), {1, "/", 2});
2204 
2205 %!assert (textscan (["1 2 3 4"; "5 6 7 8"], "%f"), {[15; 26; 37; 48]})
2206 
2207 ## Check for delimiter after exponent
2208 %!assert (textscan ("1e-3|42", "%f", "delimiter", "|"), {[1e-3; 42]})
2209 
2210 %!test <*52479>
2211 %! str = "\t\ta\tb\tc\n";
2212 %! ret = textscan (str, "%s", "delimiter", "\t");
2213 %! assert (ret, { {''; ''; 'a'; 'b'; 'c'} });
2214 
2215 %!test <52479>
2216 %! str = "\t\ta\tb\tc\n";
2217 %! ret = textscan (str, "%s", "delimiter", {"\t"});
2218 %! assert (ret, { {''; ''; 'a'; 'b'; 'c'} });
2219 
2220 %!test <52550>
2221 %! str = ",,1,2,3\n";
2222 %! obs = textscan (str, "%d", "delimiter", ",");
2223 %! assert (obs, { [0; 0; 1; 2; 3] });
2224 %! obs = textscan (str, "%d", "delimiter", {","});
2225 %! assert (obs, { [0; 0; 1; 2; 3] });
2226 
2227 %!test <52550>
2228 %! str = " , ,1,2,3\n";
2229 %! obs = textscan (str, "%d", "delimiter", ",");
2230 %! assert (obs, { [0; 0; 1; 2; 3] });
2231 %! textscan (str, "%d", "delimiter", {","});
2232 %! assert (obs, { [0; 0; 1; 2; 3] });
2233 
2234 %!test <52550>
2235 %! str = " 0 , 5+6j , -INF+INFj ,NaN,3\n";
2236 %! obs = textscan (str, "%f", "delimiter", ",");
2237 %! assert (obs, { [0; 5+6i; complex(-Inf,Inf); NaN; 3] });
2238 %! obs = textscan (str, "%f", "delimiter", {","});
2239 %! assert (obs, { [0; 5+6i; complex(-Inf,Inf); NaN; 3] });
2240 
2241 %!test <52550>
2242 %! str = " 0;,;,1;,2;,3\n";
2243 %! assert (textscan (str, "%f", "delimiter", {";,"}), { [0; NaN; 1; 2; 3] });
2244 
2245 %!test <52550>
2246 %! str = " 0 ;1 , $ 2 ;3\n";
2247 %! obs = textscan (str, "%f", "delimiter", ",;$");
2248 %! assert (obs, { [0; 1; NaN; 2; 3] });
2249 %! obs = textscan (str, "%f", "delimiter", {",",";","$"});
2250 %! assert (obs, { [0; 1; NaN; 2; 3] });
2251 
2252 */
2253 
2254 // These tests have end-comment sequences, so can't just be in a comment
2255 #if 0
2256 ## Test unfinished comment
2257 %!test
2258 %! c = textscan ("1 2 /* half comment", "%n %u8", "CommentStyle", {"/*", "*/"});
2259 %! assert (c, {1, 2});
2260 
2261 ## Test reading from a real file
2262 %!test
2263 %! f = tempname ();
2264 %! fid = fopen (f, "w+");
2265 %! d = rand (1, 4);
2266 %! fprintf (fid, " %f %f /* comment */ %f %f ", d);
2267 %! fseek (fid, 0, "bof");
2268 %! A = textscan (fid, "%f %f", "CommentStyle", {"/*", "*/"});
2269 %! E = feof (fid);
2270 %! fclose (fid);
2271 %! unlink (f);
2272 %! assert (A{1}, [d(1); d(3)], 1e-6);
2273 %! assert (A{2}, [d(2); d(4)], 1e-6);
2274 %! assert (E);
2275 #endif
2276 
2277 /*
2278 ## Test input validation
2279 %!error textscan ()
2280 %!error textscan (single (40))
2281 %!error textscan ({40})
2282 %!error <must be a string> textscan ("Hello World", 2)
2283 %!error <at most one character or>
2284 %! textscan ("Hello World", "%s", "EndOfLine", 3);
2285 %!error <'%z' is not a valid format specifier> textscan ("1.0", "%z")
2286 %!error <no valid format conversion specifiers> textscan ("1.0", "foo")
2287 */
2288 
2289 static octave_value
2290 do_fread (octave::stream& os, const octave_value& size_arg,
2291  const octave_value& prec_arg, const octave_value& skip_arg,
2292  const octave_value& arch_arg, octave_idx_type& count)
2293 {
2294  count = -1;
2295 
2296  Array<double> size = size_arg.xvector_value ("fread: invalid SIZE specified");
2297 
2298  std::string prec = prec_arg.xstring_value ("fread: PRECISION must be a string");
2299 
2300  int block_size = 1;
2301  oct_data_conv::data_type input_type;
2302  oct_data_conv::data_type output_type;
2303 
2304  try
2305  {
2306  oct_data_conv::string_to_data_type (prec, block_size,
2307  input_type, output_type);
2308  }
2309  catch (octave::execution_exception& e)
2310  {
2311  error (e, "fread: invalid PRECISION specified");
2312  }
2313 
2314  int skip = 0;
2315 
2316  try
2317  {
2318  skip = skip_arg.int_value (true);
2319  }
2320  catch (octave::execution_exception& e)
2321  {
2322  error (e, "fread: SKIP must be an integer");
2323  }
2324 
2325  std::string arch = arch_arg.xstring_value ("fread: ARCH architecture type must be a string");
2326 
2329 
2330  return os.read (size, block_size, input_type, output_type, skip,
2331  flt_fmt, count);
2332 }
2333 
2334 DEFMETHOD (fread, interp, args, ,
2335  doc: /* -*- texinfo -*-
2336 @deftypefn {} {@var{val} =} fread (@var{fid})
2337 @deftypefnx {} {@var{val} =} fread (@var{fid}, @var{size})
2338 @deftypefnx {} {@var{val} =} fread (@var{fid}, @var{size}, @var{precision})
2339 @deftypefnx {} {@var{val} =} fread (@var{fid}, @var{size}, @var{precision}, @var{skip})
2340 @deftypefnx {} {@var{val} =} fread (@var{fid}, @var{size}, @var{precision}, @var{skip}, @var{arch})
2341 @deftypefnx {} {[@var{val}, @var{count}] =} fread (@dots{})
2342 Read binary data from the file specified by the file descriptor @var{fid}.
2343 
2344 The optional argument @var{size} specifies the amount of data to read
2345 and may be one of
2346 
2347 @table @code
2348 @item Inf
2349 Read as much as possible, returning a column vector.
2350 
2351 @item @var{nr}
2352 Read up to @var{nr} elements, returning a column vector.
2353 
2354 @item [@var{nr}, Inf]
2355 Read as much as possible, returning a matrix with @var{nr} rows. If the
2356 number of elements read is not an exact multiple of @var{nr}, the last
2357 column is padded with zeros.
2358 
2359 @item [@var{nr}, @var{nc}]
2360 Read up to @code{@var{nr} * @var{nc}} elements, returning a matrix with
2361 @var{nr} rows. If the number of elements read is not an exact multiple
2362 of @var{nr}, the last column is padded with zeros.
2363 @end table
2364 
2365 @noindent
2366 If @var{size} is omitted, a value of @code{Inf} is assumed.
2367 
2368 The optional argument @var{precision} is a string specifying the type of
2369 data to read and may be one of
2370 
2371 @table @asis
2372 @item @qcode{"uint8"} (default)
2373 8-bit unsigned integer.
2374 
2375 @item @qcode{"int8"}
2376 @itemx @qcode{"integer*1"}
2377 8-bit signed integer.
2378 
2379 @item @qcode{"uint16"}
2380 @itemx @qcode{"ushort"}
2381 @itemx @qcode{"unsigned short"}
2382 16-bit unsigned integer.
2383 
2384 @item @qcode{"int16"}
2385 @itemx @qcode{"integer*2"}
2386 @itemx @qcode{"short"}
2387 16-bit signed integer.
2388 
2389 @item @qcode{"uint"}
2390 @itemx @qcode{"uint32"}
2391 @itemx @qcode{"unsigned int"}
2392 @itemx @qcode{"ulong"}
2393 @itemx @qcode{"unsigned long"}
2394 32-bit unsigned integer.
2395 
2396 @item @qcode{"int"}
2397 @itemx @qcode{"int32"}
2398 @itemx @qcode{"integer*4"}
2399 @itemx @qcode{"long"}
2400 32-bit signed integer.
2401 
2402 @item @qcode{"uint64"}
2403 64-bit unsigned integer.
2404 
2405 @item @qcode{"int64"}
2406 @itemx @qcode{"integer*8"}
2407 64-bit signed integer.
2408 
2409 @item @qcode{"single"}
2410 @itemx @qcode{"float"}
2411 @itemx @qcode{"float32"}
2412 @itemx @qcode{"real*4"}
2413 32-bit floating point number.
2414 
2415 @item @qcode{"double"}
2416 @itemx @qcode{"float64"}
2417 @itemx @qcode{"real*8"}
2418 64-bit floating point number.
2419 
2420 @item @qcode{"char"}
2421 @itemx @qcode{"char*1"}
2422 8-bit single character.
2423 
2424 @item @qcode{"uchar"}
2425 @itemx @qcode{"unsigned char"}
2426 8-bit unsigned character.
2427 
2428 @item @qcode{"schar"}
2429 @itemx @qcode{"signed char"}
2430 8-bit signed character.
2431 
2432 @end table
2433 
2434 @noindent
2435 The default precision is @qcode{"uint8"}.
2436 
2437 The @var{precision} argument may also specify an optional repeat
2438 count. For example, @samp{32*single} causes @code{fread} to read
2439 a block of 32 single precision floating point numbers. Reading in
2440 blocks is useful in combination with the @var{skip} argument.
2441 
2442 The @var{precision} argument may also specify a type conversion.
2443 For example, @samp{int16=>int32} causes @code{fread} to read 16-bit
2444 integer values and return an array of 32-bit integer values. By
2445 default, @code{fread} returns a double precision array. The special
2446 form @samp{*TYPE} is shorthand for @samp{TYPE=>TYPE}.
2447 
2448 The conversion and repeat counts may be combined. For example, the
2449 specification @samp{32*single=>single} causes @code{fread} to read
2450 blocks of single precision floating point values and return an array
2451 of single precision values instead of the default array of double
2452 precision values.
2453 
2454 The optional argument @var{skip} specifies the number of bytes to skip
2455 after each element (or block of elements) is read. If it is not
2456 specified, a value of 0 is assumed. If the final block read is not
2457 complete, the final skip is omitted. For example,
2458 
2459 @example
2460 fread (f, 10, "3*single=>single", 8)
2461 @end example
2462 
2463 @noindent
2464 will omit the final 8-byte skip because the last read will not be
2465 a complete block of 3 values.
2466 
2467 The optional argument @var{arch} is a string specifying the data format
2468 for the file. Valid values are
2469 
2470 @table @asis
2471 @item @qcode{"native"} or @qcode{"n"}
2472 The format of the current machine.
2473 
2474 @item @qcode{"ieee-be"} or @qcode{"b"}
2475 IEEE big endian.
2476 
2477 @item @qcode{"ieee-le"} or @qcode{"l"}
2478 IEEE little endian.
2479 @end table
2480 
2481 If no @var{arch} is given the value used in the call to @code{fopen} which
2482 created the file descriptor is used. Otherwise, the value specified with
2483 @code{fread} overrides that of @code{fopen} and determines the data format.
2484 
2485 The output argument @var{val} contains the data read from the file.
2486 
2487 The optional return value @var{count} contains the number of elements read.
2488 @seealso{fwrite, fgets, fgetl, fscanf, fopen}
2489 @end deftypefn */)
2490 {
2491  int nargin = args.length ();
2492 
2493  if (nargin < 1 || nargin > 5)
2494  print_usage ();
2495 
2497 
2498  octave::stream os = streams.lookup (args(0), "fread");
2499 
2500  octave_value size = lo_ieee_inf_value ();
2501  octave_value prec = "uint8";
2502  octave_value skip = 0;
2503  octave_value arch = "unknown";
2504 
2505  int idx = 1;
2506 
2507  if (nargin > idx && ! args(idx).is_string ())
2508  size = args(idx++);
2509 
2510  if (nargin > idx)
2511  prec = args(idx++);
2512 
2513  if (nargin > idx)
2514  skip = args(idx++);
2515 
2516  if (nargin > idx)
2517  arch = args(idx++);
2518  else if (skip.is_string ())
2519  {
2520  arch = skip;
2521  skip = 0;
2522  }
2523 
2524  octave_idx_type count = -1;
2525 
2526  octave_value tmp = do_fread (os, size, prec, skip, arch, count);
2527 
2528  return ovl (tmp, count);
2529 }
2530 
2531 static int
2533  const octave_value& prec_arg, const octave_value& skip_arg,
2534  const octave_value& arch_arg)
2535 {
2536  std::string prec = prec_arg.xstring_value ("fwrite: PRECISION must be a string");
2537 
2538  int block_size = 1;
2539  oct_data_conv::data_type output_type;
2540 
2541  try
2542  {
2543  oct_data_conv::string_to_data_type (prec, block_size, output_type);
2544  }
2545  catch (octave::execution_exception& e)
2546  {
2547  error (e, "fwrite: invalid PRECISION specified");
2548  }
2549 
2550  int skip = 0;
2551 
2552  try
2553  {
2554  skip = skip_arg.int_value (true);
2555  }
2556  catch (octave::execution_exception& e)
2557  {
2558  error (e, "fwrite: SKIP must be an integer");
2559  }
2560 
2561  std::string arch = arch_arg.xstring_value ("fwrite: ARCH architecture type must be a string");
2562 
2565 
2566  return os.write (data, block_size, output_type, skip, flt_fmt);
2567 }
2568 
2569 DEFMETHOD (fwrite, interp, args, ,
2570  doc: /* -*- texinfo -*-
2571 @deftypefn {} {} fwrite (@var{fid}, @var{data})
2572 @deftypefnx {} {} fwrite (@var{fid}, @var{data}, @var{precision})
2573 @deftypefnx {} {} fwrite (@var{fid}, @var{data}, @var{precision}, @var{skip})
2574 @deftypefnx {} {} fwrite (@var{fid}, @var{data}, @var{precision}, @var{skip}, @var{arch})
2575 @deftypefnx {} {@var{count} =} fwrite (@dots{})
2576 Write data in binary form to the file specified by the file descriptor
2577 @var{fid}, returning the number of values @var{count} successfully written
2578 to the file.
2579 
2580 The argument @var{data} is a matrix of values that are to be written to
2581 the file. The values are extracted in column-major order.
2582 
2583 The remaining arguments @var{precision}, @var{skip}, and @var{arch} are
2584 optional, and are interpreted as described for @code{fread}.
2585 
2586 The behavior of @code{fwrite} is undefined if the values in @var{data}
2587 are too large to fit in the specified precision.
2588 @seealso{fread, fputs, fprintf, fopen}
2589 @end deftypefn */)
2590 {
2591  int nargin = args.length ();
2592 
2593  if (nargin < 2 || nargin > 5)
2594  print_usage ();
2595 
2597 
2598  octave::stream os = streams.lookup (args(0), "fwrite");
2599 
2600  octave_value prec = "uchar";
2601  octave_value skip = 0;
2602  octave_value arch = "unknown";
2603 
2604  int idx = 1;
2605 
2606  octave_value data = args(idx++);
2607 
2608  if (nargin > idx)
2609  prec = args(idx++);
2610 
2611  if (nargin > idx)
2612  skip = args(idx++);
2613 
2614  if (nargin > idx)
2615  arch = args(idx++);
2616  else if (skip.is_string ())
2617  {
2618  arch = skip;
2619  skip = 0;
2620  }
2621 
2622  return ovl (do_fwrite (os, data, prec, skip, arch));
2623 }
2624 
2625 DEFMETHODX ("feof", Ffeof, interp, args, ,
2626  doc: /* -*- texinfo -*-
2627 @deftypefn {} {@var{status} =} feof (@var{fid})
2628 Return 1 if an end-of-file condition has been encountered for the file
2629 specified by file descriptor @var{fid} and 0 otherwise.
2630 
2631 Note that @code{feof} will only return 1 if the end of the file has already
2632 been encountered, not if the next read operation will result in an
2633 end-of-file condition.
2634 @seealso{fread, frewind, fseek, fclear, fopen}
2635 @end deftypefn */)
2636 {
2637  if (args.length () != 1)
2638  print_usage ();
2639 
2641 
2642  octave::stream os = streams.lookup (args(0), "feof");
2643 
2644  return ovl (os.eof () ? 1.0 : 0.0);
2645 }
2646 
2647 DEFMETHODX ("ferror", Fferror, interp, args, ,
2648  doc: /* -*- texinfo -*-
2649 @deftypefn {} {@var{msg} =} ferror (@var{fid})
2650 @deftypefnx {} {[@var{msg}, @var{err}] =} ferror (@var{fid})
2651 @deftypefnx {} {[@dots{}] =} ferror (@var{fid}, "clear")
2652 Query the error status of the stream specified by file descriptor @var{fid}.
2653 
2654 If an error condition exists then return a string @var{msg} describing the
2655 error. Otherwise, return an empty string @qcode{""}.
2656 
2657 The second input @qcode{"clear"} is optional. If supplied, the error
2658 state on the stream will be cleared.
2659 
2660 The optional second output is a numeric indication of the error status.
2661 @var{err} is 1 if an error condition has been encountered and 0 otherwise.
2662 
2663 Note that @code{ferror} indicates if an error has already occurred, not
2664 whether the next operation will result in an error condition.
2665 @seealso{fclear, fopen}
2666 @end deftypefn */)
2667 {
2668  int nargin = args.length ();
2669 
2670  if (nargin < 1 || nargin > 2)
2671  print_usage ();
2672 
2674 
2675  octave::stream os = streams.lookup (args(0), "ferror");
2676 
2677  bool clear = false;
2678 
2679  if (nargin == 2)
2680  {
2681  std::string opt = args(1).string_value ();
2682 
2683  clear = (opt == "clear");
2684  }
2685 
2686  int error_number = 0;
2687 
2688  std::string error_message = os.error (clear, error_number);
2689 
2690  return ovl (error_message, error_number);
2691 }
2692 
2693 DEFMETHODX ("popen", Fpopen, interp, args, ,
2694  doc: /* -*- texinfo -*-
2695 @deftypefn {} {@var{fid} =} popen (@var{command}, @var{mode})
2696 Start a process and create a pipe.
2697 
2698 The name of the command to run is given by @var{command}. The argument
2699 @var{mode} may be
2700 
2701 @table @asis
2702 @item @qcode{"r"}
2703 The pipe will be connected to the standard output of the process, and
2704 open for reading.
2705 
2706 @item @qcode{"w"}
2707 The pipe will be connected to the standard input of the process, and
2708 open for writing.
2709 @end table
2710 
2711 The file identifier corresponding to the input or output stream of the
2712 process is returned in @var{fid}.
2713 
2714 For example:
2715 
2716 @example
2717 @group
2718 fid = popen ("ls -ltr / | tail -3", "r");
2719 while (ischar (s = fgets (fid)))
2720  fputs (stdout, s);
2721 endwhile
2722 
2723  @print{} drwxr-xr-x 33 root root 3072 Feb 15 13:28 etc
2724  @print{} drwxr-xr-x 3 root root 1024 Feb 15 13:28 lib
2725  @print{} drwxrwxrwt 15 root root 2048 Feb 17 14:53 tmp
2726 @end group
2727 @end example
2728 @seealso{popen2}
2729 @end deftypefn */)
2730 {
2731  if (args.length () != 2)
2732  print_usage ();
2733 
2734  std::string name = args(0).xstring_value ("popen: COMMAND must be a string");
2735  std::string mode = args(1).xstring_value ("popen: MODE must be a string");
2736 
2738 
2740 
2741  if (mode == "r")
2742  {
2744 
2745  retval = streams.insert (ips);
2746  }
2747  else if (mode == "w")
2748  {
2750 
2751  retval = streams.insert (ops);
2752  }
2753  else
2754  error ("popen: invalid MODE specified");
2755 
2756  return retval;
2757 }
2758 
2759 DEFMETHODX ("pclose", Fpclose, interp, args, ,
2760  doc: /* -*- texinfo -*-
2761 @deftypefn {} {} pclose (@var{fid})
2762 Close a file identifier that was opened by @code{popen}.
2763 
2764 The function @code{fclose} may also be used for the same purpose.
2765 @seealso{fclose, popen}
2766 @end deftypefn */)
2767 {
2768  if (args.length () != 1)
2769  print_usage ();
2770 
2772 
2773  return ovl (streams.remove (args(0), "pclose"));
2774 }
2775 
2776 DEFUN (tempname, args, ,
2777  doc: /* -*- texinfo -*-
2778 @deftypefn {} {@var{fname} =} tempname ()
2779 @deftypefnx {} {@var{fname} =} tempname (@var{dir})
2780 @deftypefnx {} {@var{fname} =} tempname (@var{dir}, @var{prefix})
2781 Return a unique temporary filename as a string.
2782 
2783 If @var{prefix} is omitted, a value of @qcode{"oct-"} is used.
2784 
2785 If @var{dir} is also omitted, the default directory for temporary files
2786 (@code{P_tmpdir}) is used. If @var{dir} is provided, it must exist,
2787 otherwise the default directory for temporary files is used.
2788 
2789 Programming Note: Because the named file is not opened by @code{tempname},
2790 it is possible, though relatively unlikely, that it will not be available
2791 by the time your program attempts to open it. If this is a concern,
2792 see @code{tmpfile}.
2793 @seealso{mkstemp, tempdir, P_tmpdir, tmpfile}
2794 @end deftypefn */)
2795 {
2796  int nargin = args.length ();
2797 
2798  if (nargin > 2)
2799  print_usage ();
2800 
2801  std::string dir;
2802 
2803  if (nargin > 0)
2804  dir = args(0).xstring_value ("tempname: DIR must be a string");
2805  else
2806  dir = octave::sys::env::getenv ("TMPDIR");
2807 
2808  std::string pfx ("oct-");
2809 
2810  if (nargin > 1)
2811  pfx = args(1).xstring_value ("tempname: PREFIX must be a string");
2812 
2813  return ovl (octave::sys::tempnam (dir, pfx));
2814 }
2815 
2816 /*
2817 %!test
2818 %! envvar = {"TMPDIR", "TMP"};
2819 %! envdir = cellfun (@(x) getenv (x), envvar, "uniformoutput", false);
2820 %! unwind_protect
2821 %! cellfun (@(x) unsetenv (x), envvar);
2822 %! envname = "TMPDIR";
2823 %! def_tmpdir = P_tmpdir;
2824 %! ## Strip trailing file separators from P_tmpdir
2825 %! while (length (def_tmpdir) > 2 && any (def_tmpdir(end) == filesep ("all")))
2826 %! def_tmpdir(end) = [];
2827 %! endwhile
2828 %!
2829 %! ## Test 0-argument form
2830 %! fname = tempname ();
2831 %! [tmpdir, tmpfname] = fileparts (fname);
2832 %! assert (tmpdir, def_tmpdir);
2833 %! assert (tmpfname (1:4), "oct-");
2834 %! ## Test 1-argument form
2835 %! tmp_tmpdir = [def_tmpdir filesep() substr(tmpfname, -5)];
2836 %! mkdir (tmp_tmpdir) || error ("Unable to create tmp dir");
2837 %! setenv (envname, def_tmpdir);
2838 %! fname = tempname (tmp_tmpdir);
2839 %! [tmpdir, tmpfname] = fileparts (fname);
2840 %! assert (tmpdir, tmp_tmpdir);
2841 %! assert (tmpfname (1:4), "oct-");
2842 %! ## Test 1-argument form w/null tmpdir
2843 %! fname = tempname ("");
2844 %! [tmpdir, tmpfname] = fileparts (fname);
2845 %! assert (tmpdir, def_tmpdir);
2846 %! assert (tmpfname (1:4), "oct-");
2847 %! ## Test 2-argument form
2848 %! fname = tempname (tmp_tmpdir, "pfx-");
2849 %! [tmpdir, tmpfname] = fileparts (fname);
2850 %! assert (tmpdir, tmp_tmpdir);
2851 %! assert (tmpfname (1:4), "pfx-");
2852 %! ## Test 2-argument form w/null prefix
2853 %! fname = tempname (tmp_tmpdir, "");
2854 %! [tmpdir, tmpfname] = fileparts (fname);
2855 %! assert (tmpdir, tmp_tmpdir);
2856 %! assert (tmpfname (1:4), "file");
2857 %! unwind_protect_cleanup
2858 %! rmdir (tmp_tmpdir);
2859 %! for i = 1:numel (envvar)
2860 %! if (isempty (envdir{i}))
2861 %! unsetenv (envvar{i});
2862 %! else
2863 %! setenv (envvar{i}, envdir{i});
2864 %! endif
2865 %! endfor
2866 %! end_unwind_protect
2867 */
2868 
2869 DEFMETHOD (tmpfile, interp, args, ,
2870  doc: /* -*- texinfo -*-
2871 @deftypefn {} {[@var{fid}, @var{msg}] =} tmpfile ()
2872 Return the file ID corresponding to a new temporary file with a unique
2873 name.
2874 
2875 The file is opened in binary read/write (@qcode{"w+b"}) mode and will be
2876 deleted automatically when it is closed or when Octave exits.
2877 
2878 If successful, @var{fid} is a valid file ID and @var{msg} is an empty
2879 string. Otherwise, @var{fid} is -1 and @var{msg} contains a
2880 system-dependent error message.
2881 @seealso{tempname, mkstemp, tempdir, P_tmpdir}
2882 @end deftypefn */)
2883 {
2884  if (args.length () != 0)
2885  print_usage ();
2886 
2888 
2889  FILE *fid = octave_tmpfile_wrapper ();
2890 
2891  if (fid)
2892  {
2893  std::string nm;
2894 
2895  std::ios::openmode md = fopen_mode_to_ios_mode ("w+b");
2896 
2898 
2899  if (! s)
2900  {
2901  fclose (fid);
2902 
2903  error ("tmpfile: failed to create octave_stdiostream object");
2904  }
2905 
2907 
2908  retval = ovl (streams.insert (s), "");
2909  }
2910  else
2911  retval = ovl (-1, std::strerror (errno));
2912 
2913  return retval;
2914 }
2915 
2916 DEFMETHOD (mkstemp, interp, args, ,
2917  doc: /* -*- texinfo -*-
2918 @deftypefn {} {[@var{fid}, @var{name}, @var{msg}] =} mkstemp ("@var{template}")
2919 @deftypefnx {} {[@var{fid}, @var{name}, @var{msg}] =} mkstemp ("@var{template}", @var{delete})
2920 Return the file descriptor @var{fid} corresponding to a new temporary file
2921 with a unique name created from @var{template}.
2922 
2923 The last six characters of @var{template} must be @qcode{"XXXXXX"} and
2924 these are replaced with a string that makes the filename unique. The file
2925 is then created with mode read/write and permissions that are system
2926 dependent (on GNU/Linux systems, the permissions will be 0600 for versions
2927 of glibc 2.0.7 and later). The file is opened in binary mode and with the
2928 @w{@code{O_EXCL}} flag.
2929 
2930 If the optional argument @var{delete} is supplied and is true, the file will
2931 be deleted automatically when Octave exits.
2932 
2933 If successful, @var{fid} is a valid file ID, @var{name} is the name of the
2934 file, and @var{msg} is an empty string. Otherwise, @var{fid} is -1,
2935 @var{name} is empty, and @var{msg} contains a system-dependent error
2936 message.
2937 @seealso{tempname, tempdir, P_tmpdir, tmpfile, fopen}
2938 @end deftypefn */)
2939 {
2940  int nargin = args.length ();
2941 
2942  if (nargin < 1 || nargin > 2)
2943  print_usage ();
2944 
2945  std::string tmpl8 = args(0).xstring_value ("mkstemp: TEMPLATE argument must be a string");
2946 
2947  octave_value_list retval = ovl (-1, "", "");
2948 
2949  OCTAVE_LOCAL_BUFFER (char, tmp, tmpl8.size () + 1);
2950  strcpy (tmp, tmpl8.c_str ());
2951 
2952  int fd = octave_mkostemp_wrapper (tmp);
2953 
2954  if (fd < 0)
2955  {
2956  retval(0) = fd;
2957  retval(2) = std::strerror (errno);
2958  }
2959  else
2960  {
2961  const char *fopen_mode = "w+b";
2962 
2963  FILE *fid = fdopen (fd, fopen_mode);
2964 
2965  if (! fid)
2966  {
2967  retval(0) = -1;
2968  retval(2) = std::strerror (errno);
2969  }
2970  else
2971  {
2972  std::string nm = tmp;
2973 
2974  std::ios::openmode md = fopen_mode_to_ios_mode (fopen_mode);
2975 
2977 
2978  if (! s)
2979  error ("mkstemp: failed to create octave_stdiostream object");
2980 
2982 
2983  retval(0) = streams.insert (s);
2984  retval(1) = nm;
2985 
2986  if (nargin == 2 && args(1).is_true ())
2988  }
2989  }
2990 
2991  return retval;
2992 }
2993 
2994 // FIXME: This routine also exists verbatim in syscalls.cc.
2995 // Maybe change to be a general utility routine.
2996 static int
2997 convert (int x, int ibase, int obase)
2998 {
2999  int retval = 0;
3000 
3001  int tmp = x % obase;
3002 
3003  if (tmp > ibase - 1)
3004  error ("umask: invalid digit");
3005 
3006  retval = tmp;
3007  int mult = ibase;
3008  while ((x = (x - tmp) / obase))
3009  {
3010  tmp = x % obase;
3011 
3012  if (tmp > ibase - 1)
3013  error ("umask: invalid digit");
3014 
3015  retval += mult * tmp;
3016  mult *= ibase;
3017  }
3018 
3019  return retval;
3020 }
3021 
3022 DEFUNX ("umask", Fumask, args, ,
3023  doc: /* -*- texinfo -*-
3024 @deftypefn {} {} umask (@var{mask})
3025 Set the permission mask for file creation.
3026 
3027 The parameter @var{mask} is an integer, interpreted as an octal number.
3028 
3029 If successful, returns the previous value of the mask (as an integer to be
3030 interpreted as an octal number); otherwise an error message is printed.
3031 
3032 The permission mask is a UNIX concept used when creating new objects on a
3033 file system such as files, directories, or named FIFOs. The object to be
3034 created has base permissions in an octal number @var{mode} which are
3035 modified according to the octal value of @var{mask}. The final permissions
3036 for the new object are @code{@var{mode} - @var{mask}}.
3037 @seealso{fopen, mkdir, mkfifo}
3038 @end deftypefn */)
3039 {
3040  if (args.length () != 1)
3041  print_usage ();
3042 
3043  int mask = args(0).xint_value ("umask: MASK must be an integer");
3044 
3045  if (mask < 0)
3046  error ("umask: MASK must be a positive integer value");
3047 
3048  int oct_mask = convert (mask, 8, 10);
3049 
3050  int status = convert (octave::sys::umask (oct_mask), 10, 8);
3051 
3052  if (status >= 0)
3053  return ovl (status);
3054  else
3055  return ovl ();
3056 }
3057 
3058 static octave_value
3059 const_value (const char *, const octave_value_list& args, int val)
3060 {
3061  if (args.length () != 0)
3062  print_usage ();
3063 
3064  return octave_value (val);
3065 }
3066 
3067 DEFUNX ("P_tmpdir", FP_tmpdir, args, ,
3068  doc: /* -*- texinfo -*-
3069 @deftypefn {} {} P_tmpdir ()
3070 Return the name of the host system's @strong{default} directory for
3071 temporary files.
3072 
3073 Programming Note: The value returned by @code{P_tmpdir} is always the
3074 default location. This value may not agree with that returned from
3075 @code{tempdir} if the user has overridden the default with the @env{TMPDIR}
3076 environment variable.
3077 @seealso{tempdir, tempname, mkstemp, tmpfile}
3078 @end deftypefn */)
3079 {
3080  if (args.length () != 0)
3081  print_usage ();
3082 
3083  return ovl (get_P_tmpdir ());
3084 }
3085 
3086 // NOTE: the values of SEEK_SET, SEEK_CUR, and SEEK_END have to be
3087 // this way for Matlab compatibility.
3088 
3089 DEFUNX ("SEEK_SET", FSEEK_SET, args, ,
3090  doc: /* -*- texinfo -*-
3091 @deftypefn {} {} SEEK_SET ()
3092 Return the numerical value to pass to @code{fseek} to position the file pointer
3093 relative to the beginning of the file.
3094 @seealso{SEEK_CUR, SEEK_END, fseek}
3095 @end deftypefn */)
3096 {
3097  return const_value ("SEEK_SET", args, -1);
3098 }
3099 
3100 DEFUNX ("SEEK_CUR", FSEEK_CUR, args, ,
3101  doc: /* -*- texinfo -*-
3102 @deftypefn {} {} SEEK_CUR ()
3103 Return the numerical value to pass to @code{fseek} to position the file pointer
3104 relative to the current position.
3105 @seealso{SEEK_SET, SEEK_END, fseek}
3106 @end deftypefn */)
3107 {
3108  return const_value ("SEEK_CUR", args, 0);
3109 }
3110 
3111 DEFUNX ("SEEK_END", FSEEK_END, args, ,
3112  doc: /* -*- texinfo -*-
3113 @deftypefn {} {} SEEK_END ()
3114 Return the numerical value to pass to @code{fseek} to position the file pointer
3115 relative to the end of the file.
3116 @seealso{SEEK_SET, SEEK_CUR, fseek}
3117 @end deftypefn */)
3118 {
3119  return const_value ("SEEK_END", args, 1);
3120 }
3121 
3122 static octave_value
3123 const_value (const char *, const octave_value_list& args,
3124  const octave_value& val)
3125 {
3126  if (args.length () != 0)
3127  print_usage ();
3128 
3129  return octave_value (val);
3130 }
3131 
3132 DEFMETHODX ("stdin", Fstdin, interp, args, ,
3133  doc: /* -*- texinfo -*-
3134 @deftypefn {} {} stdin ()
3135 Return the numeric value corresponding to the standard input stream.
3136 
3137 When Octave is used interactively, stdin is filtered through the command
3138 line editing functions.
3139 @seealso{stdout, stderr}
3140 @end deftypefn */)
3141 {
3143 
3144  return const_value ("stdin", args, streams.stdin_file ());
3145 }
3146 
3147 DEFMETHODX ("stdout", Fstdout, interp, args, ,
3148  doc: /* -*- texinfo -*-
3149 @deftypefn {} {} stdout ()
3150 Return the numeric value corresponding to the standard output stream.
3151 
3152 Data written to the standard output may be filtered through the pager.
3153 @seealso{stdin, stderr, page_screen_output}
3154 @end deftypefn */)
3155 {
3157 
3158  return const_value ("stdout", args, streams.stdout_file ());
3159 }
3160 
3161 DEFMETHODX ("stderr", Fstderr, interp, args, ,
3162  doc: /* -*- texinfo -*-
3163 @deftypefn {} {} stderr ()
3164 Return the numeric value corresponding to the standard error stream.
3165 
3166 Even if paging is turned on, the standard error is not sent to the pager.
3167 It is useful for error messages and prompts.
3168 @seealso{stdin, stdout}
3169 @end deftypefn */)
3170 {
3172 
3173  return const_value ("stderr", args, streams.stderr_file ());
3174 }
octave_idx_type write(const octave_value &data, octave_idx_type block_size, oct_data_conv::data_type output_type, octave_idx_type skip, mach_info::float_format flt_fmt)
Definition: oct-stream.cc:6704
std::string error(bool clear, int &err_num)
Definition: oct-stream.cc:7205
std::string list_open_files(void) const
Definition: oct-stream.cc:7510
static std::ios::openmode fopen_mode_to_ios_mode(const std::string &mode)
Definition: file-io.cc:159
int insert(stream &os)
Definition: oct-stream.cc:7311
int octave_mkostemp_wrapper(char *tmpl)
stream_list & get_stream_list(void)
For example cd octave end example noindent changes the current working directory to file
Definition: dirfns.cc:124
int int_value(bool req_int=false, bool frc_str_conv=false) const
Definition: ov.h:793
#define DEFMETHOD(name, interp_name, args_name, nargout_name, doc)
Macro to define a builtin method.
Definition: defun.h:135
fname
Definition: load-save.cc:767
int flush(void)
Definition: oct-stream.cc:5996
int unlink(const std::string &name)
Definition: file-ops.cc:618
OCTINTERP_API void print_usage(void)
Definition: defun.cc:54
identity matrix If supplied two scalar respectively For allows like xample val
Definition: data.cc:4986
F77_RET_T const F77_REAL const F77_REAL F77_REAL &F77_RET_T const F77_DBLE const F77_DBLE F77_DBLE &F77_RET_T const F77_DBLE F77_DBLE &F77_RET_T const F77_REAL F77_REAL &F77_RET_T const F77_DBLE const F77_DBLE * f
std::string str(void)
Definition: oct-strstrm.h:170
string_vector get_info(int fid) const
Definition: oct-stream.cc:7467
std::string tempnam(const std::string &dir, const std::string &pfx)
Definition: file-ops.cc:638
std::string xstring_value(const char *fmt,...) const
std::string tilde_expand(const std::string &name)
Definition: file-ops.cc:276
static int do_fwrite(octave::stream &os, const octave_value &data, const octave_value &prec_arg, const octave_value &skip_arg, const octave_value &arch_arg)
Definition: file-io.cc:2532
octave_value_list retval
Definition: file-io.cc:594
octave::stream_list & streams
Definition: file-io.cc:596
void flush_stdout(void)
Definition: pager.cc:464
printf("%s\, nthargout(2, "system", "cmd"))
#define DEFUN(name, args_name, nargout_name, doc)
Macro to define a builtin function.
Definition: defun.h:53
void error(const char *fmt,...)
Definition: error.cc:578
octave_value_list splice(octave_idx_type offset, octave_idx_type len, const octave_value_list &lst=octave_value_list()) const
Definition: ovl.cc:124
float_format string_to_float_format(const std::string &s)
Definition: mach-info.cc:83
double lo_ieee_inf_value(void)
Definition: lo-ieee.cc:75
static void normalize_fopen_mode(std::string &mode, bool &use_zlib)
Definition: file-io.cc:107
octave_value textscan(const std::string &fmt, octave_idx_type ntimes, const octave_value_list &options, const std::string &who, octave_idx_type &count)
Definition: oct-stream.cc:7116
std::string getl(octave_idx_type max_len, bool &err, const std::string &who)
Definition: oct-stream.cc:6007
std::string filename
Definition: urlwrite.cc:121
octave::mach_info::float_format flt_fmt
Definition: load-save.cc:736
octave_value stdin_file(void) const
Definition: oct-stream.cc:7598
#define DEFMETHODX(name, fname, interp_name, args_name, nargout_name, doc)
Macro to define a builtin method with certain internal name.
Definition: defun.h:168
nd example oindent opens the file binary numeric values will be read assuming they are stored in IEEE format with the least significant bit and then converted to the native representation Opening a file that is already open simply opens it again and returns a separate file id It is not an error to open a file several though writing to the same file through several different file ids may produce unexpected results The possible values of text mode reading and writing automatically converts linefeeds to the appropriate line end character for the you may append a you must also open the file in binary mode The parameter conversions are currently only supported for and permissions will be set to and then everything is written in a single operation This is very efficient and improves performance c
Definition: file-io.cc:587
s
Definition: file-io.cc:2729
octave_value arch
Definition: file-io.cc:622
octave_value scanf(const std::string &fmt, const Array< double > &size, octave_idx_type &count, const std::string &who)
Definition: oct-stream.cc:7046
i e
Definition: data.cc:2591
bool is_dir(void) const
Definition: file-stat.cc:57
octave_function * fcn
Definition: ov-class.cc:1754
F77_RET_T const F77_REAL const F77_REAL F77_REAL &F77_RET_T const F77_DBLE const F77_DBLE F77_DBLE &F77_RET_T const F77_DBLE F77_DBLE &F77_RET_T const F77_REAL F77_REAL &F77_RET_T const F77_DBLE const F77_DBLE F77_DBLE * d
static std::string getenv(const std::string &name)
Definition: oct-env.cc:235
void cleanup_tmp_files(void)
Definition: file-io.cc:96
fputs(in, "these\re\ome\trings\)
stream lookup(int fid, const std::string &who="") const
Definition: oct-stream.cc:7351
std::stack< std::string > tmp_files
Definition: file-io.cc:87
nd deftypefn *std::string name
Definition: sysdep.cc:647
OCTAVE_EXPORT octave_value_list isdir nd deftypefn *std::string nm
Definition: utils.cc:975
F77_RET_T const F77_INT F77_CMPLX * A
OCTAVE_EXPORT octave_value_list return the number of command line arguments passed to Octave If called with the optional argument the function xample nargout(@histc)
Definition: ov-usr-fcn.cc:997
static octave::stream create(const std::string &n, gzFile f=nullptr, int fid=0, std::ios::openmode m=std::ios::in|std::ios::out, octave::mach_info::float_format ff=octave::mach_info::native_float_format(), c_zfile_ptr_buf::close_fcn cf=c_zfile_ptr_buf::file_close)
Definition: oct-stdstrm.h:152
OCTAVE_EXPORT octave_value_list or both For fclose
Definition: file-io.cc:676
bool is_valid(void) const
Definition: oct-stream.h:352
fclear(out)
int octave_unlink_wrapper(const char *nm)
octave_value stdout_file(void) const
Definition: oct-stream.cc:7603
off_t skipl(off_t count, bool &err, const std::string &who)
Definition: oct-stream.cc:6077
static octave::stream create(const std::string &n, std::ios::openmode arg_md=std::ios::in, octave::mach_info::float_format flt_fmt=octave::mach_info::native_float_format())
Definition: oct-prcstrm.cc:33
#define DEFUNX(name, fname, args_name, nargout_name, doc)
Macro to define a builtin function with certain internal name.
Definition: defun.h:82
std::complex< T > trunc(const std::complex< T > &x)
Definition: lo-mappers.h:120
double tmp
Definition: data.cc:6252
bool is_true(const std::string &s)
FILE * octave_tmpfile_wrapper(void)
idx type
Definition: ov.cc:3114
octave_value open_file_numbers(void) const
Definition: oct-stream.cc:7542
int puts(const std::string &s, const std::string &who)
Definition: oct-stream.cc:7162
return ovl()
With real return the complex result
Definition: data.cc:3260
int umask(mode_t mode)
Definition: file-ops.cc:613
octave_value read(const Array< double > &size, octave_idx_type block_size, oct_data_conv::data_type input_type, oct_data_conv::data_type output_type, octave_idx_type skip, mach_info::float_format flt_fmt, octave_idx_type &count)
Definition: oct-stream.cc:6507
int seek(off_t offset, int origin)
Definition: oct-stream.cc:6118
void warning(const char *fmt,...)
Definition: error.cc:801
return octave_value(v1.char_array_value() . concat(v2.char_array_value(), ra_idx),((a1.is_sq_string()||a2.is_sq_string()) ? '\'' :'"'))
int rewind(void)
Definition: oct-stream.cc:6246
int printf(const std::string &fmt, const octave_value_list &args, const std::string &who)
Definition: oct-stream.cc:7126
void mark_for_deletion(const std::string &file)
Definition: file-io.cc:90
#define octave_stdout
Definition: pager.h:174
OCTINTERP_API std::string find_data_file_in_load_path(const std::string &fcn, const std::string &file, bool require_regular_file=false)
bool is_sq_string(void) const
Definition: ov.h:580
static octave::stream create(const char *data, std::ios::openmode arg_md=std::ios::out, octave::mach_info::float_format ff=octave::mach_info::native_float_format())
Definition: oct-strstrm.cc:52
OCTINTERP_API std::string do_string_escapes(const std::string &s)
FloatComplex(* fptr)(const FloatComplex &, float, int, octave_idx_type &)
Definition: lo-specfun.cc:1129
Array< double > xvector_value(const char *fmt,...) const
int remove(int fid, const std::string &who="")
Definition: oct-stream.cc:7382
octave_value_list oscanf(const std::string &fmt, const std::string &who)
Definition: oct-stream.cc:7082
OCTAVE_EXPORT octave_value_list only variables visible in the local scope are displayed The following are valid options
Definition: variables.cc:1862
octave_idx_type length(void) const
Definition: ovl.h:96
octave_value stderr_file(void) const
Definition: oct-stream.cc:7608
#define OCTAVE_LOCAL_BUFFER(T, buf, size)
Definition: oct-locbuf.h:41
static octave::stream create(const std::string &n, FILE *f=nullptr, std::ios::openmode m=std::ios::in|std::ios::out, octave::mach_info::float_format ff=octave::mach_info::native_float_format(), c_file_ptr_buf::close_fcn cf=c_file_ptr_buf::file_close)
Definition: oct-stdstrm.h:114
octave::sys::file_stat fs(filename)
void resize(octave_idx_type n, const octave_value &rfv=octave_value())
Definition: ovl.h:100
args.length() nargin
Definition: file-io.cc:589
for i
Definition: data.cc:5264
bool is_string(void) const
Definition: ov.h:577
static data_type string_to_data_type(const std::string &s)
Definition: data-conv.cc:289
OCTAVE_EXPORT octave_value_list error nd deftypefn *const octave_scalar_map err
Definition: error.cc:1049
std::string gets(octave_idx_type max_len, bool &err, const std::string &who)
Definition: oct-stream.cc:6042
int get_file_number(const octave_value &fid) const
Definition: oct-stream.cc:7560
std::string get_P_tmpdir(void)
Definition: sysdep.cc:574
off_t tell(void)
Definition: oct-stream.cc:6235
static octave::stream create(const std::string &n, std::ios::openmode arg_md=std::ios::out, octave::mach_info::float_format flt_fmt=octave::mach_info::native_float_format())
Definition: oct-prcstrm.cc:52
Vector representing the dimensions (size) of an Array.
Definition: dim-vector.h:87
int fid
Definition: file-io.cc:625
void err_disabled_feature(const std::string &fcn, const std::string &feature, const std::string &pkg)
Definition: errwarn.cc:50
If this string is the system will ring the terminal sometimes it is useful to be able to print the original representation of the string
Definition: utils.cc:888
octave_value mode
Definition: file-io.cc:619
octave_value_list & prepend(const octave_value &val)
Definition: ovl.cc:65
octave::stream os
Definition: file-io.cc:627
bool eof(void) const
Definition: oct-stream.cc:7194
F77_RET_T const F77_REAL const F77_REAL F77_REAL &F77_RET_T const F77_DBLE const F77_DBLE F77_DBLE &F77_RET_T const F77_DBLE F77_DBLE &F77_RET_T const F77_REAL F77_REAL &F77_RET_T const F77_DBLE * x
void clearerr(void)
Definition: oct-stream.h:376
bool use_zlib
Definition: load-save.cc:769