Next Previous Contents

14. Stdio File I/O Functions

14.1 clearerr

Synopsis

Clear the error of a file stream

Usage

clearerr (File_Type fp)

Description

The clearerr function clears the error and end-of-file flags associated with the open file stream fp.

See Also

ferror, feof, fopen

14.2 fclose

Synopsis

Close a file

Usage

Integer_Type fclose (File_Type fp)

Description

The fclose function may be used to close an open file pointer fp. Upon success it returns zero, and upon failure it sets errno and returns -1. Failure usually indicates a that the file system is full or that fp does not refer to an open file.

Notes

Many C programmers call fclose without checking the return value. The S-Lang language requires the programmer to explicitly handle any value returned by a function. The simplest way to handle the return value from fclose is to call it via:

     () = fclose (fp);

See Also

fopen, fgets, fflush, pclose, errno

14.3 fdopen

Synopsis

Convert a FD_Type file descriptor to a stdio File_Type object

Usage

File_Type fdopen (FD_Type, String_Type mode)

Description

The fdopen function creates and returns a stdio File_Type object from the open FD_Type descriptor fd. The mode parameter corresponds to the mode parameter of the fopen function and must be consistent with the mode of the descriptor fd. The function returns NULL upon failure and sets errno.

Notes

Since the stdio File_Type object created by this function is derived from the FD_Type descriptor, the FD_Type is regarded as more fundamental than the File_Type object. This means that the descriptor must be in scope while the File_Type object is used. In particular, if the descriptor goes out of scope, the descriptor will get closed causing I/O to the File_Type object to fail, e.g.,

     fd = open ("/path/to/file", O_RDONLY);
     fp = fdopen (fd);
     fd = 0;     % This will cause the FD_Type descriptor to go out of
                 % scope.  Any I/O on fp will now fail.

Calling the fclose function on the File_Type object will cause the underlying descriptor to close.

Any stdio File_Type object created by the fdopen function will remain associated with the FD_Type descriptor, unless the object is explicitly removed via fclose. This means that code such as

      fd = open (...);
      loop (50)
        {
           fp = fdopen (fd, ...);
              .
              .
        }
will result in 50 File_Type objects attached to fd after the loop has terminated.

See Also

fileno, fopen, open, close, fclose, dup_fd

14.4 feof

Synopsis

Get the end-of-file status

Usage

Integer_Type feof (File_Type fp)

Description

This function may be used to determine the state of the end-of-file indicator of the open file descriptor fp. It returns zero if the indicator is not set, or non-zero if it is. The end-of-file indicator may be cleared by the clearerr function.

See Also

ferror, clearerr, fopen

14.5 ferror

Synopsis

Determine the error status of an open file descriptor

Usage

Integer_Type ferror (File_Type fp)

Description

This function may be used to determine the state of the error indicator of the open file descriptor fp. It returns zero if the indicator is not set, or non-zero if it is. The error indicator may be cleared by the clearerr function.

See Also

feof, clearerr, fopen

14.6 fflush

Synopsis

Flush an output stream

Usage

Integer_Type fflush (File_Type fp)

Description

The fflush function may be used to update the stdio output stream specified by fp. It returns 0 upon success, or -1 upon failure and sets errno accordingly. In particular, this function will fail if fp does not represent an open output stream, or if fp is associated with a disk file and there is insufficient disk space.

Example

This example illustrates how to use the fflush function without regard to the return value:

    () = fputs ("Enter value> ", stdout);
    () = fflush (stdout);

See Also

fopen, fclose

14.7 fgets

Synopsis

Read a line from a file

Usage

Integer_Type fgets (SLang_Ref_Type ref, File_Type fp)

Description

fgets reads a line from the open file specified by fp and places the characters in the variable whose reference is specified by ref. It returns -1 if fp is not associated with an open file or an attempt was made to read at the end the file; otherwise, it returns the number of characters read.

Example

The following example returns the lines of a file via a linked list:

    define read_file (file)
    {
       variable buf, fp, root, tail;
       variable list_type = struct { text, next };

       root = NULL;

       fp = fopen(file, "r");
       if (fp == NULL)
         throw OpenError, "fopen failed to open $file for reading"$;
       while (-1 != fgets (&buf, fp))
         {
            if (root == NULL)
              {
                 root = @list_type;
                 tail = root;
              }
            else
              {
                 tail.next = @list_type;
                 tail = tail.next;
              }
            tail.text = buf;
            tail.next = NULL;
         }
       () = fclose (fp);
       return root;
    }

See Also

fgetslines, fopen, fclose, fputs, fread, error

14.8 fgetslines

Synopsis

Read lines as an array from an open file

Usage

String_Type[] fgetslines (File_Type fp [,Int_Type num])

Description

The fgetslines function reads a specified number of lines as an array of strings from the file associated with the file pointer fp. If the number of lines to be read is left unspecified, the function will return the rest of the lines in the file. If the file is empty, an empty string array will be returned. The function returns NULL upon error.

Example

The following function returns the number of lines in a file:

    define count_lines_in_file (file)
    {
       variable fp, lines;

       fp = fopen (file, "r");
       if (fp == NULL)
         return -1;

       lines = fgetslines (fp);
       if (lines == NULL)
         return -1;

       return length (lines);
    }
Note that the file was implicitly closed when the variable fp goes out of scope (in the case, when the function returns).

See Also

fgets, fread, fopen, fputslines

14.9 fopen

Synopsis

Open a file

Usage

File_Type fopen (String_Type f, String_Type m)

Description

The fopen function opens a file f according to the mode string m. Allowed values for m are:

     "r"    Read only
     "w"    Write only
     "a"    Append
     "r+"   Reading and writing at the beginning of the file.
     "w+"   Reading and writing.  The file is created if it does not
              exist; otherwise, it is truncated.
     "a+"   Reading and writing at the end of the file.  The file is created
              if it does not already exist.
In addition, the mode string can also include the letter 'b' as the last character to indicate that the file is to be opened in binary mode.

Upon success, fopen returns a File_Type object which is meant to be used by other operations that require an open file pointer. Upon failure, the function returns NULL.

Example

The following function opens a file in append mode and writes a string to it:

    define append_string_to_file (str, file)
    {
       variable fp = fopen (file, "a");
       if (fp == NULL)
         throw OpenError, "$file could not be opened"$;
       () = fputs (str, fp);
       () = fclose (fp);
    }
Note that the return values from fputs and fclose were ignored.

Notes

There is no need to explicitly close a file opened with fopen. If the returned File_Type object goes out of scope, the interpreter will automatically close the file. However, explicitly closing a file with fclose and checking its return value is recommended.

See Also

fclose, fgets, fputs, popen

14.10 fprintf

Synopsis

Create and write a formatted string to a file

Usage

Int_Type fprintf (File_Type fp, String_Type fmt, ...)

Description

fprintf formats the objects specified by the variable argument list according to the format fmt and write the result to the open file pointer fp.

The format string obeys the same syntax and semantics as the sprintf format string. See the description of the sprintf function for more information.

fprintf returns the number of bytes written to the file, or -1 upon error.

See Also

fputs, printf, fwrite, message

14.11 fputs

Synopsis

Write a string to an open stream

Usage

Integer_Type fputs (String_Type s, File_Type fp)

Description

The fputs function writes the string s to the open file pointer fp. It returns -1 upon failure and sets errno, otherwise it returns the length of the string.

Example

The following function opens a file in append mode and uses the fputs function to write to it.

    define append_string_to_file (str, file)
    {
       variable fp;
       fp = fopen (file, "a");
       if (fp == NULL)
         throw OpenError, "Unable to open $file"$;
       if ((-1 == fputs (str, fp))
           || (-1 == fclose (fp)))
         throw WriteError, "Error writing to $file"$;
    }

Notes

One must not disregard the return value from the fputs function. Doing so may lead to a stack overflow error.

To write an object that contains embedded null characters, use the fwrite function.

See Also

fclose, fopen, fgets, fwrite

14.12 fputslines

Synopsis

Write an array of strings to an open file

Usage

Int_Type fputslines (String_Type[]a, File_Type fp)

Description

The fputslines function writes an array of strings to the specified file pointer. It returns the number of elements successfully written. Any NULL elements in the array will be skipped.

Example

    if (length (lines) != fputslines (lines, fp))
      throw WriteError;

See Also

fputs, fgetslines, fopen

14.13 fread

Synopsis

Read binary data from a file

Usage

UInt_Type fread (Ref_Type b, DataType_Type t, UInt_Type n, File_Type fp)

Description

The fread function may be used to read n objects of type t from an open file pointer fp. Upon success, it returns the number of objects read from the file and places the objects in variable specified by b. Upon error or end-of-file, it returns -1 and sets errno accordingly.

If more than one object is read from the file, those objects will be placed in an array of the appropriate size.

Example

The following example illustrates how to read 50 integers from a file:

     define read_50_ints_from_a_file (file)
     {
        variable fp, n, buf;

        fp = fopen (file, "rb");
        if (fp == NULL)
          throw OpenError;
        n = fread (&buf, Int_Type, 50, fp);
        if (n == -1)
          throw ReadError, "fread failed";
        () = fclose (fp);
        return buf;
     }

Notes

Use the pack and unpack functions to read data with a specific byte-ordering.

The fread_bytes function may be used to read a specified number of bytes in the form of a binary string (BString_Type).

If an attempt is made to read at the end of a file, the function will return -1. To distinguish this condition from a system error, the feof function should be used. This distinction is particularly important when reading from a socket or pipe.

See Also

fread_bytes, fwrite, fgets, feof, ferror, fopen, pack, unpack

14.14 fread_bytes

Synopsis

Read bytes from a file as a binary-string

Usage

UInt_Type fread_bytes (Ref_Type b, UInt_Type n, File_Type fp)

Description

The fread_bytes function may be used to read n bytes from from an open file pointer fp. Upon success, it returns the number of bytes read from the file and assigns to the variable attached to the reference b a binary string formed from the bytes read. Upon error or end of file, the function returns -1 and sets errno accordingly.

Notes

Use the pack and unpack functions to read data with a specific byte-ordering.

See Also

fread, fwrite, fgets, fopen, pack, unpack

14.15 fseek

Synopsis

Reposition a stdio stream

Usage

Integer_Type fseek (File_Type fp, LLong_Type ofs, Integer_Type whence)

Description

The fseek function may be used to reposition the file position pointer associated with the open file stream fp. Specifically, it moves the pointer ofs bytes relative to the position indicated by whence. If whence is set to one of the symbolic constants SEEK_SET, SEEK_CUR, or SEEK_END, the offset is relative to the start of the file, the current position indicator, or end-of-file, respectively.

The function returns 0 upon success, or -1 upon failure and sets errno accordingly.

Example

define rewind (fp) { if (0 == fseek (fp, 0, SEEK_SET)) return; vmessage ("rewind failed, reason: %s", errno_string (errno)); }

See Also

ftell, fopen

14.16 ftell

Synopsis

Obtain the current position in an open stream

Usage

LLong_Type ftell (File_Type fp)

Description

The ftell function may be used to obtain the current position in the stream associated with the open file pointer fp. It returns the position of the pointer measured in bytes from the beginning of the file. Upon error, it returns -1 and sets errno accordingly.

See Also

fseek, fopen

14.17 fwrite

Synopsis

Write binary data to a file

Usage

UInt_Type fwrite (b, File_Type fp)

Description

The fwrite function may be used to write the object represented by b to an open file. If b is a string or an array, the function will attempt to write all elements of the object to the file. It returns the number of elements successfully written, otherwise it returns -1 upon error and sets errno accordingly.

Example

The following example illustrates how to write an integer array to a file. In this example, fp is an open file descriptor:

     variable a = [1:50];     % 50 element integer array
     if (50 != fwrite (a, fp))
       throw WriteError;
Here is how to write the array one element at a time:
     variable ai, a = [1:50];

     foreach ai (a)
       {
          if (1 != fwrite(ai, fp))
            throw WriteError;
       }

Notes

Not all data types may be supported the fwrite function. It is supported by all vector, scalar, and string objects.

See Also

fread, fputs, fopen, pack, unpack

14.18 pclose

Synopsis

Close a process pipe

Usage

Integer_Type pclose (File_Type fp)

Description

The pclose function waits for the process associated with fp to exit and then returns the exit status of the command.

See Also

popen, fclose

14.19 popen

Synopsis

Open a pipe to a process

Usage

File_Type popen (String_Type cmd, String_Type mode)

Description

The popen function executes a process specified by cmd and opens a unidirectional pipe to the newly created process. The mode indicates whether or not the pipe is open for reading or writing. Specifically, if mode is "r", then the pipe is opened for reading, or if mode is "w", then the pipe will be open for writing.

Upon success, a File_Type pointer will be returned, otherwise the function failed and NULL will be returned.

Notes

This function is not available on all systems.

The process module's new_process function provides a much more secure and powerful interface to process I/O.

See Also

<@@ref>new_processnew_process, pclose, fopen

14.20 printf

Synopsis

Create and write a formatted string to stdout

Usage

Int_Type printf (String_Type fmt, ...)

Description

printf formats the objects specified by the variable argument list according to the format fmt and write the result to stdout. This function is equivalent to fprintf used with the stdout file pointer. See fprintf for more information.

printf returns the number of bytes written or -1 upon error.

Notes

Many C programmers do not check the return status of the printf C library function. Make sure that if you do not care about whether or not the function succeeds, then code it as in the following example:

     () = printf ("%s laid %d eggs\n", chicken_name, num_egg);

See Also

fputs, fprintf, fwrite, message

14.21 setvbuf

Synopsis
Usage

Int_Type setvbuf (File_Type fp, Int_Type mode, Int_Type size)

Description

The setvbuf function may be used to control how the stdio stream specified by the open File_Type object is buffered.

The mode argument must be one of the following values:

   _IONBF   : unbuffered
   _IOFBF   : fully buffered
   _IOLBF   : line buffered
The size argument controls the size of the buffer. If size is 0, then the function will not change the size of the buffer, only the mode. Otherwise, size is expected to be larger than 0 and a buffer of the requested size will be allocated for the stream. are buffered.

Notes

This function must be used only after the stream has been opened and before any other operations have been performed on the stream.

See Also

fopen, fclose, fflush


Next Previous Contents