C file input/output: Difference between revisions

Content deleted Content added
huge cleanup, merge from fgetc, recat
No edit summary
Tags: Mobile edit Mobile app edit iOS app edit App section source
 
(396 intermediate revisions by more than 100 users not shown)
Line 1:
{{short description|Input/output functionality in the C programming language}}
The [[C (programming language)|C programming language]] provides many [[standard library]] [[subroutine|functions]] for [[computer file|file]] [[input/output|input and output]]. These functions make up the bulk of the [[C standard library]] [[header file|header]] <code><[[stdio.h]]></code>.
{{Use dmy dates|date=February 2022}}
{{C Standard Library}}
The [[C (programming language)|C programming language]] provides many [[standard library]] [[subroutine|functions]] for [[computer file|file]] [[input/output|input and output]]. These functions make up the bulk of the [[C standard library]] [[header file|header]] {{mono|<'''stdio.h'''>}}.<ref>{{cite book |title=ISO/IEC 9899:1999 specification |at=p. 274, § 7.19 |language=en-US}}</ref> The functionality descends from a "portable I/O package" written by [[Mike Lesk]] at [[Bell Labs]] in the early 1970s,<ref>{{cite book |last1=Kernighan |first1=Brian |author-link1=Brian Kernighan |last2=Pike |first2=Rob |author-link2=Rob Pike |title=[[The UNIX Programming Environment]] |publisher=[[Prentice Hall]] |___location=[[Englewood Cliffs]] |year=1984 |page=200|bibcode=1984upe..book.....K }}</ref> and officially became part of the [[Unix]] operating system in [[Version 7 Unix|Version 7]].<ref name="reader">{{cite tech report |first1=M. D. |last1=McIlroy |author-link1=Doug McIlroy |year=1987 |url=http://www.cs.dartmouth.edu/~doug/reader.pdf |title=A Research Unix reader: annotated excerpts from the Programmer's Manual, 1971–1986 |series=CSTR |number=139 |institution=Bell Labs}}</ref>
 
The I/O functionality of C is fairly low-level by modern standards; C abstracts all file operations into operations on [[stream (computercomputing)|stream]]s of [[byte]]s, which may be "input streams" or "output streams". Unlike some earlier programming languages, C has no direct support for [[random access|random-access]] data files; to read from a record in the middle of a file, the programmer must create a stream, [[fseek|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 the [[Unix]] [[operating system]], 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 [[:Category:C programming language family|C programming language family]] have inherited C's file I/O interface with few if any changes (for example, [[PHP]]). The [[C++]] standard library reflects the "stream" concept in its syntax; see [[iostream]].
 
==Overview==
==Opening a file using fopen==
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.<ref>{{Cite web |title=(stdio.h) - C++ Reference |url=http://www.cplusplus.com/reference/cstdio/ |access-date=July 25, 2021 |website=C++ |language=en-US}}</ref>
A file is opened using <code>'''fopen'''</code>, which returns an I/O [[stream (computer)|stream]] attached to the specified file or other device from which reading and writing can be done. If the function fails, it returns a [[null pointer]].
 
===Functions===
The related C library function <code>'''freopen'''</code> performs the same operation after first closing any open stream associated with its parameter.
Most of the C file input/output functions are defined in {{mono|<stdio.h>}} (or in the [[C++]] header {{mono|cstdio}}, which contains the standard C functionality but in the {{mono|std}} [[namespace]]).
 
{| class="wikitable"
They are defined as
|-
:<code>FILE *fopen(const char *path, const char *mode);</code>
!
:<code>FILE *freopen(const char *path, const char *mode, FILE *fp);</code>
! Byte<br />character
 
! Wide<br />character
The <code>fopen</code> function is essentially a slightly higher-level wrapper for the <code>open</code> [[system call]] of [[Unix]] [[operating system]]s. In the same way, <code>fclose</code> is often a thin wrapper for the Unix system call <code>close</code>, and the C <code>FILE</code> structure itself often corresponds to a Unix [[file descriptor]]. In [[POSIX]] environments, the <code>'''fdopen'''</code> function can be used to initialize a <code>FILE</code> structure from a file descriptor; however, file descriptors are a purely Unix concept not present in standard C.
! Description
|-
! rowspan=9 | File access
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|fopen}}[https://en.cppreference.com/w/c/io/fopen fopen]
| Opens a file (with a non-Unicode filename on Windows and possible UTF-8 filename on Linux)
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|popen}}[https://man7.org/linux/man-pages/man3/popen.3.html popen]
| opens a process by creating a pipe, forking, and invoking the shell
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|freopen}}[https://en.cppreference.com/w/c/io/freopen freopen]
| Opens a different file with an existing stream
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|fflush}}[https://en.cppreference.com/w/c/io/fflush fflush]
| Synchronizes an output stream with the actual file
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|fclose}}[https://en.cppreference.com/w/c/io/fclose fclose]
| Closes a file
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|pclose}}[https://man7.org/linux/man-pages/man3/pclose.3p.html pclose]
| closes a stream
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|setbuf}}[https://en.cppreference.com/w/c/io/setbuf setbuf]
| Sets the buffer for a file stream
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|setvbuf}}[https://en.cppreference.com/w/c/io/setvbuf setvbuf]
| Sets the buffer and its size for a file stream
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|fwide}}[https://en.cppreference.com/w/c/io/fwide fwide]
| Switches a file stream between wide-character I/O and narrow-character I/O
|-
! rowspan=2 | Direct <br /> input/output
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|fread}}[https://en.cppreference.com/w/c/io/fread fread]
| Reads from a file
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|fwrite}}[https://en.cppreference.com/w/c/io/fwrite fwrite]
| Writes to a file
|-
! rowspan=9 | Unformatted <br /> input/output
| style="font-family:monospace" | {{anchor|fgetc|getc}}[https://en.cppreference.com/w/c/io/fgetc fgetc]<br />[https://en.cppreference.com/w/c/io/getc getc]
| style="font-family:monospace"| {{anchor|fgetwc|getwc}}[https://en.cppreference.com/w/c/io/fgetwc fgetwc]<br />[https://en.cppreference.com/w/c/io/getwc getwc]
| Reads a byte/{{mono|wchar_t}} from a file stream
|-
| style="font-family:monospace" | {{anchor|fgets}}[https://en.cppreference.com/w/c/io/fgets fgets]
| style="font-family:monospace" | {{anchor|fgetws}}[https://en.cppreference.com/w/c/io/fgetws fgetws]
| Reads a byte/{{mono|wchar_t}} line from a file stream
|-
| style="font-family:monospace" | {{anchor|fputc|putc}}[https://en.cppreference.com/w/c/io/fputc fputc]<br />[https://en.cppreference.com/w/c/io/putc putc]
| style="font-family:monospace" | {{anchor|fputwc|putwc}}[https://en.cppreference.com/w/c/io/fputwc fputwc]<br />[https://en.cppreference.com/w/c/io/putwc putwc]
| Writes a byte/{{mono|wchar_t}} to a file stream
|-
| style="font-family:monospace" | {{anchor|fputs}}[https://en.cppreference.com/w/c/io/fputs fputs]
| style="font-family:monospace" | {{anchor|fputws}}[https://en.cppreference.com/w/c/io/fputws fputws]
| Writes a byte/{{mono|wchar_t}} string to a file stream
|-
| style="font-family:monospace" | {{anchor|getchar}}[https://en.cppreference.com/w/c/io/getchar getchar]
| style="font-family:monospace" | {{anchor|getwchar}}[https://en.cppreference.com/w/c/io/getwchar getwchar]
| Reads a byte/{{mono|wchar_t}} from stdin
|-
| style="font-family:monospace" | {{anchor|gets}}<s>[https://en.cppreference.com/w/c/io/gets gets]</s>
| {{n/a}}
| Reads a byte string from stdin until a newline or end of file is encountered (deprecated in C99, removed from C11)
|-
| style="font-family:monospace" | {{anchor|putchar}}[https://en.cppreference.com/w/c/io/putchar putchar]
| style="font-family:monospace" | {{anchor|putwchar}}[https://en.cppreference.com/w/c/io/putwchar putwchar]
| Writes a byte/{{mono|wchar_t}} to stdout
|-
| style="font-family:monospace" | {{anchor|puts}}[https://en.cppreference.com/w/c/io/puts puts]
| {{n/a}}
| Writes a byte string to stdout
|-
| style="font-family:monospace" | {{anchor|ungetc}}[https://en.cppreference.com/w/c/io/ungetc ungetc]
| style="font-family:monospace" | {{anchor|ungetwc}}[https://en.cppreference.com/w/c/io/ungetwc ungetwc]
| Puts a byte/{{mono|wchar_t}} back into a file stream
|-
! rowspan=5 | Formatted <br /> input/output
| style="font-family:monospace" | {{anchor|scanf|fscanf|sscanf}}[https://en.cppreference.com/w/c/io/scanf scanf]<br />[https://en.cppreference.com/w/c/io/fscanf fscanf]<br />[https://en.cppreference.com/w/c/io/sscanf sscanf]
| style="font-family:monospace" | {{anchor|wscanf|fwscanf|swscanf}}[https://en.cppreference.com/w/c/io/wscanf wscanf]<br />[https://en.cppreference.com/w/c/io/fwscanf fwscanf]<br />[https://en.cppreference.com/w/c/io/swscanf swscanf]
| Reads formatted byte/{{mono|wchar_t}} input from stdin,<br />a file stream or a buffer
|-
| style="font-family:monospace" | {{anchor|vscanf|vfscanf|vsscanf}}[https://en.cppreference.com/w/c/io/vscanf vscanf]<br />[https://en.cppreference.com/w/c/io/vfscanf vfscanf]<br />[https://en.cppreference.com/w/c/io/vsscanf vsscanf]
| style="font-family:monospace" | {{anchor|vwscanf|vfwscanf|vswscanf}}[https://en.cppreference.com/w/c/io/vwscanf vwscanf]<br />[https://en.cppreference.com/w/c/io/vfwscanf vfwscanf]<br />[https://en.cppreference.com/w/c/io/vswscanf vswscanf]
| Reads formatted input byte/{{mono|wchar_t}} from stdin,<br />a file stream or a buffer using variable argument list
|-
| style="font-family:monospace" | {{anchor|printf|fprintf|sprintf|snprintf}}[https://en.cppreference.com/w/c/io/printf printf]<br />[https://en.cppreference.com/w/c/io/fprintf fprintf]<br />[https://en.cppreference.com/w/c/io/sprintf sprintf]<br />[https://en.cppreference.com/w/c/io/snprintf snprintf]
| style="font-family:monospace" | {{anchor|wprintf|fwprintf|swprintf}}[https://en.cppreference.com/w/c/io/wprintf wprintf]<br />[https://en.cppreference.com/w/c/io/fwprintf fwprintf]<br />[https://en.cppreference.com/w/c/io/swprintf swprintf]
| Prints formatted byte/{{mono|wchar_t}} output to stdout,<br />a file stream or a buffer
|-
| style="font-family:monospace" | {{anchor|vprintf|vfprintf|vsprintf|vsnprintf}}[https://en.cppreference.com/w/c/io/vprintf vprintf]<br />[https://en.cppreference.com/w/c/io/vfprintf vfprintf]<br />[https://en.cppreference.com/w/c/io/vsprintf vsprintf]<br />[https://en.cppreference.com/w/c/io/vsnprintf vsnprintf]
| style="font-family:monospace" | {{anchor|vwprintf|vfwprintf|vswprintf}}[https://en.cppreference.com/w/c/io/vwprintf vwprintf]<br />[https://en.cppreference.com/w/c/io/vfwprintf vfwprintf]<br />[https://en.cppreference.com/w/c/io/vfwprintf vswprintf]
| Prints formatted byte/{{mono|wchar_t}} output to stdout,<br />a file stream, or a buffer using variable argument list
|-
| style="font-family:monospace" | {{anchor|perror}}[https://en.cppreference.com/w/c/io/perror perror]
| {{n/a}}
| Writes a description of the [[errno.h|current error]] to stderr
|-
! rowspan=5 | File positioning
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|ftell}}[https://en.cppreference.com/w/c/io/ftell ftell]<br/>ftello
| Returns the current file position indicator
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|fseek}}[https://en.cppreference.com/w/c/io/fseek fseek]<br/>fseeko
| Moves the file position indicator to a specific ___location in a file
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|fgetpos}}[https://en.cppreference.com/w/c/io/fgetpos fgetpos]
| Gets the file position indicator
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|fsetpos}}[https://en.cppreference.com/w/c/io/fsetpos fsetpos]
| Moves the file position indicator to a specific ___location in a file
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|rewind}}[https://en.cppreference.com/w/c/io/rewind rewind]
| Moves the file position indicator to the beginning in a file
|-
! rowspan=3 | Error<br />handling
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|clearerr}}[https://en.cppreference.com/w/c/io/clearerr clearerr]
| Clears errors
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|feof}}[https://en.cppreference.com/w/c/io/feof feof]
| Checks for the end-of-file
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|ferror}}[https://en.cppreference.com/w/c/io/ferror ferror]
| Checks for a file error
|-
! rowspan=4 | Operations <br />on files
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|remove}}[https://en.cppreference.com/w/c/io/remove remove]
| Erases a file
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|rename}}[https://en.cppreference.com/w/c/io/rename rename]
| [[rename (computing)|Rename]]s a file
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|tmpfile}}[https://en.cppreference.com/w/c/io/tmpfile tmpfile]
| Returns a pointer to a temporary file
|-
| colspan=2 style="text-align:center;font-family:monospace" | {{anchor|tmpnam}}[https://en.cppreference.com/w/c/io/tmpnam tmpnam]
| Returns a unique filename
|}
 
===Constants===
The <code>mode</code> parameter to <code>fopen</code> and <code>freopen</code> must be a [[C string|string]] that begins with one of the following sequences:
Constants defined in the {{mono|<stdio.h>}} header include:
 
{| class="wikitable"
|-
! Name !! Notes
!colspan=3| mode || description || starts..
|-
! style="font-family:monospace" | [[End-of-file|EOF]]
|<tt>r</tt> || <tt>rb</tt> || || open for reading || beginning
| A negative integer of type {{mono|int}} used to indicate end-of-file conditions
|-
! style="font-family:monospace" | {{Anchor|BUFSIZ}} [http://c-p-p.net/c/stdio.h/bufsiz BUFSIZ]
|<tt>w</tt> || <tt>wb</tt> || || open for writing (creates file if it doesn't exist). Deletes content and overwrites the file. || beginning
| An integer which is the size of the buffer used by the {{mono|setbuf()}} function
|-
! style="font-family:monospace" | FILENAME_MAX
|<tt>a</tt> || <tt>ab</tt> || || open for appending (creates file if it doesn't exist) || end
| The size of a {{mono|char}} array which is large enough to store the name of any file that can be opened
|-
! style="font-family:monospace" | FOPEN_MAX
|<tt>r+</tt> || <tt>rb+</tt> || <tt>r+b</tt> || open for reading and writing || beginning
| The number of files that may be open simultaneously; will be at least eight
|-
! style="font-family:monospace" | _IOFBF
|<tt>w+</tt> || <tt>wb+</tt> || <tt>w+b</tt> || open for reading and writing. Deletes content and overwrites the file. || beginning
| An abbreviation for "input/output fully buffered"; it is an integer which may be passed to the {{mono|setvbuf()}} function to request ''block buffered'' input and output for an open stream
|-
! style="font-family:monospace" | _IOLBF
|<tt>a+</tt> || <tt>ab+</tt> || <tt>a+b</tt> || open for reading and writing (append if file exists) || end
| An abbreviation for "input/output line buffered"; it is an integer which may be passed to the {{mono|setvbuf()}} function to request ''line buffered'' input and output for an open stream
|-
! style="font-family:monospace" | _IONBF
| An abbreviation for "input/output not buffered"; it is an integer which may be passed to the {{mono|setvbuf()}} function to request ''unbuffered'' input and output for an open stream
|-
! style="font-family:monospace" | L_tmpnam
| The size of a {{mono|char}} array which is large enough to store a temporary filename generated by the {{mono|tmpnam()}} function
|-
! style="font-family:monospace" | 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
|-
! style="font-family:monospace" | SEEK_CUR
| An integer which may be passed to the {{mono|fseek()}} function to request positioning relative to the current file position
|-
! style="font-family:monospace" | SEEK_END
| An integer which may be passed to the {{mono|fseek()}} function to request positioning relative to the end of the file
|-
! style="font-family:monospace" | SEEK_SET
| An integer which may be passed to the {{mono|fseek()}} function to request positioning relative to the beginning of the file
|-
! style="font-family:monospace" | TMP_MAX
| The maximum number of unique filenames generable by the {{mono|tmpnam()}} function; will be at least 25
|}
 
===Variables===
The "<tt>b</tt>" stands for '''b'''inary. The C standard provides for two kinds of files &mdash; [[text file]]s and [[binary file]]s &mdash; although operating systems are not required to distinguish between the two. A ''text file'' is a file consisting of text arranged in lines with some sort of distinguishing [[newline|end-of-line]] character or sequence (in [[Unix]], a bare [[line feed]] character; in [[Microsoft Windows]], a [[carriage return]] followed by a line feed). When bytes are read in from a text file, an end-of-line sequence is usually mapped to a linefeed for ease in processing. When a text file is written to, a bare linefeed is mapped to the OS-specific end-of-line character sequence before writing. A ''binary file'' is a file where bytes are read in "raw", and delivered "raw", without any kind of mapping.
[[File:Stdstreams-notitle.svg|frameless|right]]
Variables defined in the {{mono|<stdio.h>}} header include:
 
{| class="wikitable"
When a file is opened with update mode ( '<tt>+</tt>' as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, writes cannot be followed by reads without an intervening call to <code>fflush</code> or to a file positioning function ( <code>[[fseek]]</code>, <code>fsetpos</code>, or <code>[[Rewind (C)|rewind]]</code>), and reads cannot be followed by writes without an intervening call to a file positioning function. [http://www.opengroup.org/onlinepubs/009695399/functions/fopen.html]
|-
! Name !! Notes
|-
! style="font-family:monospace" | [[Standard streams#Standard input (stdin)|stdin]]
| A pointer to a {{mono|FILE}} which refers to the standard input stream, usually a keyboard.
|-
! style="font-family:monospace" | [[Standard streams#Standard output (stdout)|stdout]]
| A pointer to a {{mono|FILE}} which refers to the standard output stream, usually a display terminal.
|-
! style="font-family:monospace" | [[Standard streams#Standard error (stderr)|stderr]]
| A pointer to a {{mono|FILE}} which refers to the standard error stream, often a display terminal.
|}
 
===Member types===
Writing and appending modes will attempt to create a file of the given name, if no such file already exists. As mentioned above, if this operation fails, <code>fopen</code> will return <code>[[NULL]]</code>.
Data types defined in the {{mono|<stdio.h>}} header include:
*{{mono|[https://en.cppreference.com/w/c/io FILE]}} – also known as a {{anchor|file handle}}'''file [[Handle (computing)|handle]]''' or a '''{{Visible anchor|FILE pointer}}''', 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 mbstate_t)
**reentrant lock (required as of [[C11 (C standard revision)|C11]])
*{{mono|fpos_t}} – 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
*{{mono|size_t}} – an [[unsigned integer]] type which is the type of the result of the {{mono|[[sizeof]]}} operator.
 
===Extensions{{anchor|POSIX}}===
==Closing a stream using fclose==
The [[POSIX]] standard defines several extensions to {{mono|stdio}} in its Base Definitions, among which are a {{mono|readline}} function that allocates memory, the {{mono|fileno}} and {{mono|fdopen}} functions that establish the link between {{mono|FILE}} objects and [[file descriptor]]s, and a group of functions for creating {{mono|FILE}} objects that refer to in-memory buffers.<ref>{{man|bd|stdio.h|SUS}}</ref>
The <code>fclose</code> function takes one argument: a [[pointer]] to the <code>FILE</code> structure of the stream to close.
 
==Example==
:<code>int fclose(FILE *fp);</code>
The following C program opens a binary file called ''myfile'', reads five bytes from it, and then closes the file.
 
<syntaxhighlight lang="c">
The function returns [[zero]] on success, or [[end-of-file|EOF]] on failure.
#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
==Reading from a stream using fgetc==
char buffer[5];
The <code>'''fgetc'''</code> function is used to read a character from a stream.
size_t len;
FILE* fp = fopen("myfile", "rb");
 
if (fp == NULL) {
:<code>int fgetc(FILE *fp);</code>
perror("Failed to open file \"myfile\"");
return EXIT_FAILURE;
}
 
if ((len = fread(buffer, 1, 5, fp)) < 0) {
If successful, <code>fgetc</code> returns the next byte or character from the stream (depending on whether the file is "binary" or "text", as discussed under <code>fopen</code> above). If unsuccessful, fgetc returns <code>[[end-of-file|EOF]]</code>. (The exact type of error can be determined by calling <code>ferror</code> or <code>feof</code> with the file pointer.)
fclose(fp);
fputs("An error occurred while reading the file.\n", stderr);
return EXIT_FAILURE;
}
 
fclose(fp);
The standard [[macro]] <code>'''getc'''</code>, also defined in <code><stdio.h></code>, behaves in almost the same way as <code>fgetc</code>, except that &mdash; being a macro &mdash; it may evaluate its arguments more than once.
 
printf("The bytes read were: ");
The standard function <code>'''getchar'''</code>, also defined in <code><stdio.h></code>, takes no arguments, and is equivalent to <code>fgetc([[stdin]])</code>.
for (int i = 0; i < len; ++i) {
printf("%02X ", buffer[i]);
}
putchar('\n');
 
return EXIT_SUCCESS;
==Writing to a stream using fputc==
}
The <code>'''fputc'''</code> function is used to write a character to a stream.
</syntaxhighlight>
 
==Alternatives to stdio{{anchor|Sfio}}==
:<code>int fputc(int c, FILE *fp);</code>
{{Redirect|Sfio|other uses of "SFIO"|SFIO (disambiguation)}}
 
Several alternatives to {{mono|stdio}} have been developed. Among these are [[Input/output (C++)|C++ I/O]] headers <code><iostream></code> and <code><print></code>, part of the [[ISO C++|ISO C++ standard]]. ISO C++ still requires the {{mono|stdio}} functionality.
The parameter <code>c</code> is silently converted to an <code>unsigned char</code> before being output. If successful, <code>fputc</code> returns the character written. If unsuccessful, fputc returns <code>EOF</code>.
 
Other alternatives include the Sfio<ref>{{Cite web |url=http://akpublic.research.att.com/sw/tools/sfio/ |title=Sfio: A Safe/Fast I/O Library |access-date=16 March 2021 |archive-date=11 February 2006 |archive-url=https://web.archive.org/web/20060211021834/http://akpublic.research.att.com/sw/tools/sfio/ |url-status=bot: unknown }}</ref> (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 {{mono|stdio}}. Among its features is the possibility to insert [[callback function]]s into a stream to customize the handling of data read from or written to the stream.<ref>{{cite conference |title=SFIO: Safe/Fast String/File IO |first1=David G. |last1=Korn |author-link=David Korn (computer scientist) |first2=Kiem-Phong |last2=Vo |conference=Proc. Summer USENIX Conf. |year=1991 |citeseerx=10.1.1.51.6574}}</ref> It was released to the outside world in 1997, and the last release was 1 February 2005.<ref>{{cite conference |first1=Glenn S. |last1=Fowler |first2=David G. |last2=Korn |first3=Kiem-Phong |last3=Vo |title=Extended Formatting with Sfio |conference=Proc. Summer USENIX Conf. |year=2000}}</ref>
The standard [[macro]] <code>'''putc'''</code>, also defined in <code><stdio.h></code>, behaves in almost the same way as <code>fputc</code>, except that &mdash; being a macro &mdash; it may evaluate its arguments more than once.
 
The standard function <code>'''putchar'''</code>, also defined in <code><stdio.h></code>, takes only the first argument, and is equivalent to <code>fputc(''c'', [[stdout]])</code> where <code>''c''</code> is that argument.
 
==Example usage==
The following C program opens a binary file called ''myfile.dat'', reads five bytes from it, and then closes the file.
<code>
[[#include]] <stdio.h>
int main(void)
{
char buffer[5] = {0}; /* initialized to zeros */
int i;
FILE *fp = fopen("myfile.dat", "wb");
if (fp == NULL) {
[[printf]]("The file didn't open.\n");
return 0;
}
for (i=0; i < 5; ++i) {
int rc = fgetc(fp);
if (rc == EOF) {
printf("There was an error reading the file.\n");
break;
}
buffer[i] = rc;
}
fclose(fp);
if (i == 5) {
printf("The bytes read were...\n");
putchar(buffer[0]);
putchar(buffer[1]);
putchar(buffer[2]);
putchar(buffer[3]);
putchar(buffer[4]);
putc('\n', stdout);
}
return 0;
}
</code>
 
==See also==
*<code>[[printf format string]]</code>
*[[scanf format string]]
 
==References==
{{Reflist}}
 
==External links==
{{wikibooks|C Programming|C file input and output|C Programming/C Reference}}
*[http://www.gamedev.net/reference/articles/article1127.asp Gamedev article on C++ file I/O], including ways of handling binary files
*{{Commons category-inline}}
*{{man|3|fclose}}
*{{man|3|fgetc}}
*{{man|3|fopen}}
*{{man|3|fputc}}
 
{{CProLang}}
[[Category:stdio.h]]
[[Category:Input/Output]]
[[Category:Articles with example C code]]
 
{{DEFAULTSORT:C file input output}}
[[ja:Fgetc]]
[[Category:C standard library]]
[[Category:Input/output]]
[[Category:Articles with example C code]]