Jump to content

C file input/output

From Wikipedia, the free encyclopedia
(Redirected from Sfio)

Template:Short description Template:Use dmy dates Template:C Standard Library The C programming language provides many standard library functions for file input and output. These functions make up the bulk of the C standard library header Template:Mono.[1] The functionality descends from a "portable I/O package" written by Mike Lesk at Bell Labs in the early 1970s,[2] and officially became part of the Unix operating system in Version 7.[3]

The I/O functionality of C is fairly low-level by modern standards; C abstracts all file operations into operations on streams of bytes, which may be "input streams" or "output streams". Unlike some earlier programming languages, C has no direct support for random-access data files; to read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream.

The stream model of file I/O was popularized by Unix, which was developed concurrently with the C programming language itself. The vast majority of modern operating systems have inherited streams from Unix, and many languages in the C programming language family have inherited C's file I/O interface with few if any changes (for example, PHP).

Overview

This library uses what are called streams to operate with physical devices such as keyboards, printers, terminals or with any other type of files supported by the system. Streams are an abstraction to interact with these in a uniform way. All streams have similar properties independent of the individual characteristics of the physical media they are associated with.[4]

Functions

Most of the C file input/output functions are defined in <syntaxhighlight lang="text" class="" style="" inline="1"><stdio.h></syntaxhighlight> (or in the C++ header <syntaxhighlight lang="text" class="" style="" inline="1"><cstdio></syntaxhighlight>, which contains the standard C functionality but in the Template:Mono namespace).

Byte
character
Wide
character
Description
File access {{safesubst:#invoke:anchor|main}}fopen Opens a file (with a non-Unicode filename on Windows and possible UTF-8 filename on Linux)
{{safesubst:#invoke:anchor|main}}popen opens a process by creating a pipe, forking, and invoking the shell
{{safesubst:#invoke:anchor|main}}freopen Opens a different file with an existing stream
{{safesubst:#invoke:anchor|main}}fflush Synchronizes an output stream with the actual file
{{safesubst:#invoke:anchor|main}}fclose Closes a file
{{safesubst:#invoke:anchor|main}}pclose closes a stream
{{safesubst:#invoke:anchor|main}}setbuf Sets the buffer for a file stream
{{safesubst:#invoke:anchor|main}}setvbuf Sets the buffer and its size for a file stream
{{safesubst:#invoke:anchor|main}}fwide Switches a file stream between wide-character I/O and narrow-character I/O
Direct
input/output
{{safesubst:#invoke:anchor|main}}fread Reads from a file
{{safesubst:#invoke:anchor|main}}fwrite Writes to a file
Unformatted
input/output
{{safesubst:#invoke:anchor|main}}fgetc
getc
{{safesubst:#invoke:anchor|main}}fgetwc
getwc
Reads a byte/Template:Mono from a file stream
{{safesubst:#invoke:anchor|main}}fgets {{safesubst:#invoke:anchor|main}}fgetws Reads a byte/Template:Mono line from a file stream
{{safesubst:#invoke:anchor|main}}fputc
putc
{{safesubst:#invoke:anchor|main}}fputwc
putwc
Writes a byte/Template:Mono to a file stream
{{safesubst:#invoke:anchor|main}}fputs {{safesubst:#invoke:anchor|main}}fputws Writes a byte/Template:Mono string to a file stream
{{safesubst:#invoke:anchor|main}}getchar {{safesubst:#invoke:anchor|main}}getwchar Reads a byte/Template:Mono from stdin
{{safesubst:#invoke:anchor|main}}gets Template:N/a Reads a byte string from stdin until a newline or end of file is encountered (deprecated in C99, removed from C11)
{{safesubst:#invoke:anchor|main}}putchar {{safesubst:#invoke:anchor|main}}putwchar Writes a byte/Template:Mono to stdout
{{safesubst:#invoke:anchor|main}}puts Template:N/a Writes a byte string to stdout
{{safesubst:#invoke:anchor|main}}ungetc {{safesubst:#invoke:anchor|main}}ungetwc Puts a byte/Template:Mono back into a file stream
Formatted
input/output
{{safesubst:#invoke:anchor|main}}scanf
fscanf
sscanf
{{safesubst:#invoke:anchor|main}}wscanf
fwscanf
swscanf
Reads formatted byte/Template:Mono input from stdin,
a file stream or a buffer
{{safesubst:#invoke:anchor|main}}vscanf
vfscanf
vsscanf
{{safesubst:#invoke:anchor|main}}vwscanf
vfwscanf
vswscanf
Reads formatted input byte/Template:Mono from stdin,
a file stream or a buffer using variable argument list
{{safesubst:#invoke:anchor|main}}printf
fprintf
sprintf
snprintf
{{safesubst:#invoke:anchor|main}}wprintf
fwprintf
swprintf
Prints formatted byte/Template:Mono output to stdout,
a file stream or a buffer
{{safesubst:#invoke:anchor|main}}vprintf
vfprintf
vsprintf
vsnprintf
{{safesubst:#invoke:anchor|main}}vwprintf
vfwprintf
vswprintf
Prints formatted byte/Template:Mono output to stdout,
a file stream, or a buffer using variable argument list
{{safesubst:#invoke:anchor|main}}perror Template:N/a Writes a description of the current error to stderr
File positioning {{safesubst:#invoke:anchor|main}}ftell
ftello
Returns the current file position indicator
{{safesubst:#invoke:anchor|main}}fseek
fseeko
Moves the file position indicator to a specific location in a file
{{safesubst:#invoke:anchor|main}}fgetpos Gets the file position indicator
{{safesubst:#invoke:anchor|main}}fsetpos Moves the file position indicator to a specific location in a file
{{safesubst:#invoke:anchor|main}}rewind Moves the file position indicator to the beginning in a file
Error
handling
{{safesubst:#invoke:anchor|main}}clearerr Clears errors
{{safesubst:#invoke:anchor|main}}feof Checks for the end-of-file
{{safesubst:#invoke:anchor|main}}ferror Checks for a file error
Operations
on files
{{safesubst:#invoke:anchor|main}}remove Erases a file
{{safesubst:#invoke:anchor|main}}rename Renames a file
{{safesubst:#invoke:anchor|main}}tmpfile Returns a pointer to a temporary file
{{safesubst:#invoke:anchor|main}}tmpnam Returns a unique filename

Constants

Constants defined in the <syntaxhighlight lang="text" class="" style="" inline="1"><stdio.h></syntaxhighlight> header include:

Name Notes
EOF A negative integer of type Template:Mono used to indicate end-of-file conditions
{{safesubst:#invoke:anchor|main}} BUFSIZ An integer which is the size of the buffer used by the Template:Mono function
FILENAME_MAX The size of a Template:Mono array which is large enough to store the name of any file that can be opened
FOPEN_MAX The number of files that may be open simultaneously; will be at least eight
_IOFBF An abbreviation for "input/output fully buffered"; it is an integer which may be passed to the Template:Mono function to request block buffered input and output for an open stream
_IOLBF An abbreviation for "input/output line buffered"; it is an integer which may be passed to the Template:Mono function to request line buffered input and output for an open stream
_IONBF An abbreviation for "input/output not buffered"; it is an integer which may be passed to the Template:Mono function to request unbuffered input and output for an open stream
L_tmpnam The size of a Template:Mono array which is large enough to store a temporary filename generated by the Template:Mono function
NULL A macro expanding to the null pointer constant; that is, a constant representing a pointer value which is guaranteed not to be a valid address of an object in memory
SEEK_CUR An integer which may be passed to the Template:Mono function to request positioning relative to the current file position
SEEK_END An integer which may be passed to the Template:Mono function to request positioning relative to the end of the file
SEEK_SET An integer which may be passed to the Template:Mono function to request positioning relative to the beginning of the file
TMP_MAX The maximum number of unique filenames generable by the Template:Mono function; will be at least 25

Variables

File:Stdstreams-notitle.svg

Variables defined in the <syntaxhighlight lang="text" class="" style="" inline="1"><stdio.h></syntaxhighlight> header include:

Name Notes
stdin A pointer to a Template:Mono which refers to the standard input stream, usually a keyboard.
stdout A pointer to a Template:Mono which refers to the standard output stream, usually a display terminal.
stderr A pointer to a Template:Mono which refers to the standard error stream, often a display terminal.

Member types

Data types defined in the <syntaxhighlight lang="text" class="" style="" inline="1"><stdio.h></syntaxhighlight> header include:

  • Template:Mono – also known as a {{safesubst:#invoke:anchor|main}}file handle or a Template:Visible anchor, this is an opaque pointer containing the information about a file or text stream needed to perform input or output operations on it, including:
    • platform-specific identifier of the associated I/O device, such as a file descriptor
    • the buffer
    • stream orientation indicator (unset, narrow, or wide)
    • stream buffering state indicator (unbuffered, line buffered, fully buffered)
    • I/O mode indicator (input stream, output stream, or update stream)
    • binary/text mode indicator
    • end-of-file indicator
    • error indicator
    • the current stream position and multibyte conversion state (an object of type <syntaxhighlight lang="text" class="" style="" inline="1">mbstate_t</syntaxhighlight>)
    • reentrant lock (required as of C11)
  • <syntaxhighlight lang="text" class="" style="" inline="1">fpos_t</syntaxhighlight> – a non-array type capable of uniquely identifying the position of every byte in a file and every conversion state that can occur in all supported multibyte character encodings
  • <syntaxhighlight lang="text" class="" style="" inline="1">size_t</syntaxhighlight> – an unsigned integer type which is the type of the result of the Template:Mono operator.

Extensions

The POSIX standard defines several extensions to <syntaxhighlight lang="text" class="" style="" inline="1"><stdio.h></syntaxhighlight> in its Base Definitions, among which are a <syntaxhighlight lang="text" class="" style="" inline="1">readline</syntaxhighlight> function that allocates memory, the <syntaxhighlight lang="text" class="" style="" inline="1">fileno</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">fdopen</syntaxhighlight> functions that establish the link between Template:Mono objects and file descriptors, and a group of functions for creating <syntaxhighlight lang="text" class="" style="" inline="1">FILE</syntaxhighlight> objects that refer to in-memory buffers.[5]

Example

The following C program opens a binary file called Template:Mono, reads five bytes from it, and then closes the file.

<syntaxhighlight lang="c">

  1. include <stdio.h>
  2. include <stdlib.h>

int main(void) {

   const char file_name[] = "myfile.bin";
   char buffer[5];
   FILE* fp = fopen(file_name, "rb");
   if (fp == NULL) {
       fprintf(stderr, "Failed to open file \"%s\"!\n", file_name);
       return EXIT_FAILURE;
   }
   size_t len = fread(buffer, 1, sizeof buffer, fp);
   if (len < sizeof buffer) {
       if (ferror(fp)) {
           fprintf(stderr, "Read error in \"%s\"\n", file_name);
       } else if (feof(fp)) {
           fprintf(stderr, "Unexpected end of file in \"%s\"\n", file_name);
       }
       fclose(fp);
       return EXIT_FAILURE;
   }
   fclose(fp);
   printf("The bytes read were: ");
   for (size_t i = 0; i < len; ++i) {
       printf("%02X ", (unsigned char)buffer[i]);
   }
   putchar('\n');
   return EXIT_SUCCESS;

} </syntaxhighlight>

Alternatives to stdio

{{#invoke:redirect hatnote|redirect|1}}

Several alternatives to <syntaxhighlight lang="text" class="" style="" inline="1"><stdio.h></syntaxhighlight> have been developed. Among these are C++ I/O headers <iostream> and <print>, part of the C++ Standard Library. ISO C++ still requires the <syntaxhighlight lang="text" class="" style="" inline="1"><stdio.h></syntaxhighlight> functionality, and it is found under header <cstdio>.

Other alternatives include the Sfio[6] (A Safe/Fast I/O Library) library from AT&T Bell Laboratories. This library, introduced in 1991, aimed to avoid inconsistencies, unsafe practices and inefficiencies in the design of <syntaxhighlight lang="text" class="" style="" inline="1"><stdio.h></syntaxhighlight>. Among its features is the possibility to insert callback functions into a stream to customize the handling of data read from or written to the stream.[7][8] It was released to the outside world in 1997, and the last official stable release was 2005-02-01[9][10][11]

See also

References

Template:Reflist

Template:Sister project

Template:CProLang

  1. ↑ Template:Cite book
  2. ↑ Template:Cite book
  3. ↑ Template:Cite tech report
  4. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
  5. ↑ Template:Man
  6. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
  7. ↑ Template:Cite conference
  8. ↑ Template:Cite conference
  9. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
  10. ↑ sfio-2005-02-01
  11. ↑ sfio-AST-2012-08-01