From Surf Wiki (app.surf) — the open knowledge base
C file input/output
Input/output functionality in the C programming language
Input/output functionality in the C programming language
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 . The functionality descends from a "portable I/O package" written by Mike Lesk at Bell Labs in the early 1970s, and officially became part of the Unix operating system in Version 7.
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.
Functions
Most of the C file input/output functions are defined in (or in the C++ header , which contains the standard C functionality but in the namespace).
| Byte | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| character | Wide | ||||||||
| character | Description | File access | Direct | ||||||
| input/output | Unformatted | ||||||||
| input/output | Formatted | ||||||||
| input/output | File positioning | Error | |||||||
| handling | Operations | ||||||||
| on files | |||||||||
| fopenfopen | Opens a file (with a non-Unicode filename on Windows and possible UTF-8 filename on Linux) | ||||||||
| popenpopen | opens a process by creating a pipe, forking, and invoking the shell | ||||||||
| freopenfreopen | Opens a different file with an existing stream | ||||||||
| fflushfflush | Synchronizes an output stream with the actual file | ||||||||
| fclosefclose | Closes a file | ||||||||
| pclosepclose | closes a stream | ||||||||
| setbufsetbuf | Sets the buffer for a file stream | ||||||||
| setvbufsetvbuf | Sets the buffer and its size for a file stream | ||||||||
| fwidefwide | Switches a file stream between wide-character I/O and narrow-character I/O | ||||||||
| freadfread | Reads from a file | ||||||||
| fwritefwrite | Writes to a file | ||||||||
| fgetcfgetc | |||||||||
| getc | fgetwcfgetwc | ||||||||
| getwc | Reads a byte/ from a file stream | ||||||||
| fgetsfgets | fgetwsfgetws | Reads a byte/ line from a file stream | |||||||
| fputcfputc | |||||||||
| putc | fputwcfputwc | ||||||||
| putwc | Writes a byte/ to a file stream | ||||||||
| fputsfputs | fputwsfputws | Writes a byte/ string to a file stream | |||||||
| getchargetchar | getwchargetwchar | Reads a byte/ from stdin | |||||||
| getsgets | Reads a byte string from stdin until a newline or end of file is encountered (deprecated in C99, removed from C11) | ||||||||
| putcharputchar | putwcharputwchar | Writes a byte/ to stdout | |||||||
| putsputs | Writes a byte string to stdout | ||||||||
| ungetcungetc | ungetwcungetwc | Puts a byte/ back into a file stream | |||||||
| scanfscanf | |||||||||
| fscanf | |||||||||
| sscanf | wscanfwscanf | ||||||||
| fwscanf | |||||||||
| swscanf | Reads formatted byte/ input from stdin, | ||||||||
| a file stream or a buffer | |||||||||
| vscanfvscanf | |||||||||
| vfscanf | |||||||||
| vsscanf | vwscanfvwscanf | ||||||||
| vfwscanf | |||||||||
| vswscanf | Reads formatted input byte/ from stdin, | ||||||||
| a file stream or a buffer using variable argument list | |||||||||
| printfprintf | |||||||||
| fprintf | |||||||||
| sprintf | |||||||||
| snprintf | wprintfwprintf | ||||||||
| fwprintf | |||||||||
| swprintf | Prints formatted byte/ output to stdout, | ||||||||
| a file stream or a buffer | |||||||||
| vprintfvprintf | |||||||||
| vfprintf | |||||||||
| vsprintf | |||||||||
| vsnprintf | vwprintfvwprintf | ||||||||
| vfwprintf | |||||||||
| vswprintf | Prints formatted byte/ output to stdout, | ||||||||
| a file stream, or a buffer using variable argument list | |||||||||
| perrorperror | Writes a description of the current error to stderr | ||||||||
| ftellftell | |||||||||
| ftello | Returns the current file position indicator | ||||||||
| fseekfseek | |||||||||
| fseeko | Moves the file position indicator to a specific location in a file | ||||||||
| fgetposfgetpos | Gets the file position indicator | ||||||||
| fsetposfsetpos | Moves the file position indicator to a specific location in a file | ||||||||
| rewindrewind | Moves the file position indicator to the beginning in a file | ||||||||
| clearerrclearerr | Clears errors | ||||||||
| feoffeof | Checks for the end-of-file | ||||||||
| ferrorferror | Checks for a file error | ||||||||
| removeremove | Erases a file | ||||||||
| renamerename | Renames a file | ||||||||
| tmpfiletmpfile | Returns a pointer to a temporary file | ||||||||
| tmpnamtmpnam | Returns a unique filename |
Constants
Constants defined in the header include:
| Name | Notes | EOF | BUFSIZ BUFSIZ | FILENAME_MAX | FOPEN_MAX | _IOFBF | _IOLBF | _IONBF | L_tmpnam | NULL | SEEK_CUR | SEEK_END | SEEK_SET | TMP_MAX |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| A negative integer of type used to indicate end-of-file conditions | ||||||||||||||
| An integer which is the size of the buffer used by the function | ||||||||||||||
| The size of a array which is large enough to store the name of any file that can be opened | ||||||||||||||
| The number of files that may be open simultaneously; will be at least eight | ||||||||||||||
| An abbreviation for "input/output fully buffered"; it is an integer which may be passed to the function to request block buffered input and output for an open stream | ||||||||||||||
| An abbreviation for "input/output line buffered"; it is an integer which may be passed to the function to request line buffered input and output for an open stream | ||||||||||||||
| An abbreviation for "input/output not buffered"; it is an integer which may be passed to the function to request unbuffered input and output for an open stream | ||||||||||||||
| The size of a array which is large enough to store a temporary filename generated by the function | ||||||||||||||
| 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 | ||||||||||||||
| An integer which may be passed to the function to request positioning relative to the current file position | ||||||||||||||
| An integer which may be passed to the function to request positioning relative to the end of the file | ||||||||||||||
| An integer which may be passed to the function to request positioning relative to the beginning of the file | ||||||||||||||
| The maximum number of unique filenames generable by the function; will be at least 25 |
Variables
Variables defined in the header include:
| Name | Notes | stdin | stdout | stderr |
|---|---|---|---|---|
| A pointer to a which refers to the standard input stream, usually a keyboard. | ||||
| A pointer to a which refers to the standard output stream, usually a display terminal. | ||||
| A pointer to a which refers to the standard error stream, often a display terminal. |
Member types
Data types defined in the header include:
- – also known as a file handlefile handle or a ** 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 )
- reentrant lock (required as of C11)
- – 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
- – an unsigned integer type which is the type of the result of the operator.
Extensions{{anchor|POSIX}}
The POSIX standard defines several extensions to in its Base Definitions, among which are a function that allocates memory, the and functions that establish the link between objects and file descriptors, and a group of functions for creating objects that refer to in-memory buffers.
Example
The following C program opens a binary file called , reads five bytes from it, and then closes the file.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char buffer[5];
size_t len;
FILE* fp = fopen("myfile", "rb");
if (fp == NULL) {
perror("Failed to open file \"myfile\"");
return EXIT_FAILURE;
}
if ((len = fread(buffer, 1, 5, fp)) < 0) {
fclose(fp);
fputs("An error occurred while reading the file.\n", stderr);
return EXIT_FAILURE;
}
fclose(fp);
printf("The bytes read were: ");
for (int i = 0; i < len; ++i) {
printf("%02X ", buffer[i]);
}
putchar('\n');
return EXIT_SUCCESS;
}Alternatives to stdio{{anchor|Sfio}}
Several alternatives to have been developed. Among these are C++ I/O headers and, part of the C++ Standard Library. ISO C++ still requires the functionality, and it is found under header ``.
Other alternatives include the Sfio (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 . 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. It was released to the outside world in 1997, and the last official stable release was 2005-02-01
References
References
- "ISO/IEC 9899:1999 specification".
- (1984). "[[The UNIX Programming Environment]]". [[Prentice Hall]].
- (1987). "A Research Unix reader: annotated excerpts from the Programmer's Manual, 1971–1986".
- "(stdio.h) - C++ Reference".
- {{man. bd. stdio.h. SUS
- "Sfio: A Safe/Fast I/O Library".
- (1991). "SFIO: Safe/Fast String/File IO".
- (2000). "Extended Formatting with Sfio".
- "sfio Software Download Package List".
- [https://github.com/lichray/sfio sfio-2005-02-01]
- [https://github.com/att/ast/tree/master/src/lib/libast/sfio sfio-AST-2012-08-01]
This article was imported from Wikipedia and is available under the Creative Commons Attribution-ShareAlike 4.0 License. Content has been adapted to SurfDoc format. Original contributors can be found on the article history page.
Ask Mako anything about C file input/output — get instant answers, deeper analysis, and related topics.
Research with MakoFree with your Surf account
Create a free account to save articles, ask Mako questions, and organize your research.
Sign up freeThis content may have been generated or modified by AI. CloudSurf Software LLC is not responsible for the accuracy, completeness, or reliability of AI-generated content. Always verify important information from primary sources.
Report