World Library  
Flag as Inappropriate
Email this Article

C file input/output

Article Id: WHEBN0000238766
Reproduction Date:

Title: C file input/output  
Author: World Heritage Encyclopedia
Language: English
Subject: Input/output, C character classification, C mathematical functions, C string handling, C dynamic memory allocation
Collection: Articles with Example C Code, C Standard Library, Input/Output
Publisher: World Heritage Encyclopedia
Publication
Date:
 

C file input/output

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 .[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).

Contents

  • Overview 1
    • Functions 1.1
    • Constants 1.2
    • Variables 1.3
    • Member types 1.4
    • Extensions 1.5
  • Example 2
  • Alternatives to stdio 3
  • See also 4
  • References 5
  • External links 6

Overview

Functions

Most of the C file input/output functions are defined in stdio.h (or in the C++ header cstdio, which contains the standard C functionality but in the std namespace).

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

Constants

Constants defined in the stdio.h header include:

Name Notes
EOF A negative integer of type int used to indicate end-of-file conditions
BUFSIZ An integer which is the size of the buffer used by the setbuf() function
FILENAME_MAX The size of a char 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 setvbuf() 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 setvbuf() 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 setvbuf() function to request unbuffered input and output for an open stream
L_tmpnam The size of a char array which is large enough to store a temporary filename generated by the tmpnam() 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 fseek() function to request positioning relative to the current file position
SEEK_END An integer which may be passed to the fseek() function to request positioning relative to the end of the file
SEEK_SET An integer which may be passed to the fseek() function to request positioning relative to the beginning of the file
TMP_MAX The maximum number of unique filenames generable by the tmpnam() function; will be at least 25

Variables

Variables defined in the stdio.h header include:

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

Member types

Data types defined in the stdio.h header include:

  • FILE - also known as a file handle, this is an opaque type containing the information about a file or text stream needed to perform input or output operations on it, including:
    • a file descriptor
    • the current stream position
    • an end-of-file indicator
    • an error indicator
    • a pointer to the stream's buffer, if applicable
  • fpos_t - a non-array type capable of uniquely identifying the position of every byte in a file.
  • size_t - an unsigned integer type which is the type of the result of the sizeof operator.

Extensions

The POSIX standard defines several extensions to stdio in its Base Definitions, among which are a readline function that allocates memory, the fileno and fdopen functions that establish the link between FILE objects and file descriptors, and a group of functions for creating FILE objects that refer to in-memory buffers.[4]

Example

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

#include 
#include 

int main(void)
{
    char buffer[5] = {0};  /* Initialized to zeroes */
    int i;
    FILE *fp = fopen("myfile", "rb");

    if (fp == NULL) {
        perror("Failed to open file \"myfile\"");
        return EXIT_FAILURE;
    }

    for (i = 0; i < 5; i++) {
        int rc = getc(fp);
        if (rc == EOF) {
            fputs("An error occurred while reading the file.\n", stderr);
            return EXIT_FAILURE;
        }
        buffer[i] = rc;
    }

    fclose(fp);

    printf("The bytes read were... %x %x %x %x %x\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4]);

    return EXIT_SUCCESS;
}

Alternatives to stdio

Several alternatives to stdio have been developed. Among these is the C++ iostream library, part of the ISO C++ standard. ISO C++ still requires the stdio functionality.

Other alternatives include the Sfio (safe/fast string/file I/O) library from AT&T Bell Laboratories. This library, introduced in 1991, aimed to avoid inconsistencies, unsafe practices and inefficiencies in the design of stdio. 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.[5] It was released to the outside world in 1997.[6]

See also

References

  1. ^ ISO/IEC 9899:1999 specification (PDF). p. 274, § 7.19. 
  2. ^  
  3. ^  
  4. ^  – Base Definitions Reference, The Single UNIX® Specification, Issue 7 from The Open Group
  5. ^  
  6. ^ Fowler, Glenn S.; Korn, David G.; Vo, Kiem-Phong (2000). Extended Formatting with Sfio. Proc. Summer USENIX Conf. 

External links

This article was sourced from Creative Commons Attribution-ShareAlike License; additional terms may apply. World Heritage Encyclopedia content is assembled from numerous content providers, Open Access Publishing, and in compliance with The Fair Access to Science and Technology Research Act (FASTR), Wikimedia Foundation, Inc., Public Library of Science, The Encyclopedia of Life, Open Book Publishers (OBP), PubMed, U.S. National Library of Medicine, National Center for Biotechnology Information, U.S. National Library of Medicine, National Institutes of Health (NIH), U.S. Department of Health & Human Services, and USA.gov, which sources content from all federal, state, local, tribal, and territorial government publication portals (.gov, .mil, .edu). Funding for USA.gov and content contributors is made possible from the U.S. Congress, E-Government Act of 2002.
 
Crowd sourced content that is contributed to World Heritage Encyclopedia is peer reviewed and edited by our editorial staff to ensure quality scholarly research articles.
 
By using this site, you agree to the Terms of Use and Privacy Policy. World Heritage Encyclopedia™ is a registered trademark of the World Public Library Association, a non-profit organization.
 


Copyright © World Library Foundation. All rights reserved. eBooks from Project Gutenberg are sponsored by the World Library Foundation,
a 501c(4) Member's Support Non-Profit Organization, and is NOT affiliated with any governmental agency or department.