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