Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

C file input/output

From Wikipedia, the free encyclopedia
(Redirected fromFopen)
Input/output functionality in the C programming language

C standard library (libc)
General topics
Miscellaneous headers

TheC programming language provides manystandard libraryfunctions forfileinput and output. These functions make up the bulk of theC standard libraryheader<stdio.h>.[1] The functionality descends from a "portable I/O package" written byMike Lesk atBell Labs in the early 1970s,[2] and officially became part of theUnix operating system inVersion 7.[3]

The I/O functionality of C is fairly low-level by modern standards; C abstracts all file operations into operations onstreams ofbytes, which may be "input streams" or "output streams". Unlike some earlier programming languages, C has no direct support forrandom-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 theC programming language family have inherited C's file I/O interface with few if any changes (for example,PHP).

Overview

[edit]

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

[edit]

Most of the C file input/output functions are defined in<stdio.h> (or in theC++ headercstdio, which contains the standard C functionality but in thestdnamespace).

Byte
character
Wide
character
Description
File accessfopenOpens a file (with a non-Unicode filename on Windows and possible UTF-8 filename on Linux)
popenopens a process by creating a pipe, forking, and invoking the shell
freopenOpens a different file with an existing stream
fflushSynchronizes an output stream with the actual file
fcloseCloses a file
pclosecloses a stream
setbufSets the buffer for a file stream
setvbufSets the buffer and its size for a file stream
fwideSwitches a file stream between wide-character I/O and narrow-character I/O
Direct
input/output
freadReads from a file
fwriteWrites to a file
Unformatted
input/output
fgetc
getc
fgetwc
getwc
Reads a byte/wchar_t from a file stream
fgetsfgetwsReads a byte/wchar_t line from a file stream
fputc
putc
fputwc
putwc
Writes a byte/wchar_t to a file stream
fputsfputwsWrites a byte/wchar_t string to a file stream
getchargetwcharReads a byte/wchar_t from stdin
getsReads a byte string from stdin until a newline or end of file is encountered (deprecated in C99, removed from C11)
putcharputwcharWrites a byte/wchar_t to stdout
putsWrites a byte string to stdout
ungetcungetwcPuts 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
perrorWrites a description of thecurrent error to stderr
File positioningftell
ftello
Returns the current file position indicator
fseek
fseeko
Moves the file position indicator to a specific location in a file
fgetposGets the file position indicator
fsetposMoves the file position indicator to a specific location in a file
rewindMoves the file position indicator to the beginning in a file
Error
handling
clearerrClears errors
feofChecks for the end-of-file
ferrorChecks for a file error
Operations
on files
removeErases a file
renameRenames a file
tmpfileReturns a pointer to a temporary file
tmpnamReturns a unique filename

Constants

[edit]

Constants defined in the<stdio.h> header include:

NameNotes
EOFA negative integer of typeint used to indicate end-of-file conditions
BUFSIZAn integer which is the size of the buffer used by thesetbuf() function
FILENAME_MAXThe size of achar array which is large enough to store the name of any file that can be opened
FOPEN_MAXThe number of files that may be open simultaneously; will be at least eight
_IOFBFAn abbreviation for "input/output fully buffered"; it is an integer which may be passed to thesetvbuf() function to requestblock buffered input and output for an open stream
_IOLBFAn abbreviation for "input/output line buffered"; it is an integer which may be passed to thesetvbuf() function to requestline buffered input and output for an open stream
_IONBFAn abbreviation for "input/output not buffered"; it is an integer which may be passed to thesetvbuf() function to requestunbuffered input and output for an open stream
L_tmpnamThe size of achar array which is large enough to store a temporary filename generated by thetmpnam() function
NULLA macro expanding to thenull pointer constant; that is, a constant representing a pointer value which is guaranteednot to be a valid address of an object in memory
SEEK_CURAn integer which may be passed to thefseek() function to request positioning relative to the current file position
SEEK_ENDAn integer which may be passed to thefseek() function to request positioning relative to the end of the file
SEEK_SETAn integer which may be passed to thefseek() function to request positioning relative to the beginning of the file
TMP_MAXThe maximum number of unique filenames generable by thetmpnam() function; will be at least 25

Variables

[edit]

Variables defined in the<stdio.h> header include:

NameNotes
stdinA pointer to aFILE which refers to the standard input stream, usually a keyboard.
stdoutA pointer to aFILE which refers to the standard output stream, usually a display terminal.
stderrA pointer to aFILE which refers to the standard error stream, often a display terminal.

Member types

[edit]

Data types defined in the<stdio.h> header include:

  • FILE – also known as afilehandle or aFILE pointer, this is anopaque 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 afile 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 ofC11)
  • 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
  • size_t – anunsigned integer type which is the type of the result of thesizeof operator.

Extensions

[edit]

ThePOSIX standard defines several extensions tostdio in its Base Definitions, among which are areadline function that allocates memory, thefileno andfdopen functions that establish the link betweenFILE objects andfile descriptors, and a group of functions for creatingFILE objects that refer to in-memory buffers.[5]

Example

[edit]

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

#include<stdio.h>#include<stdlib.h>intmain(void){charbuffer[5];FILE*fp=fopen("myfile","rb");if(fp==NULL){perror("Failed to open file\"myfile\"");returnEXIT_FAILURE;}if(fread(buffer,1,5,fp)<5){fclose(fp);fputs("An error occurred while reading the file.\n",stderr);returnEXIT_FAILURE;}fclose(fp);printf("The bytes read were: ");for(inti=0;i<5;++i){printf("%02X ",buffer[i]);}putchar('\n');returnEXIT_SUCCESS;}

Alternatives to stdio

[edit]
"Sfio" redirects here. For other uses of "SFIO", seeSFIO (disambiguation).

Several alternatives tostdio have been developed. Among these is theC++iostream library, part of theISO C++ standard. ISO C++ still requires thestdio functionality.

Other alternatives include the Sfio[6] (A Safe/Fast I/O Library) library fromAT&T Bell Laboratories. This library, introduced in 1991, aimed to avoid inconsistencies, unsafe practices and inefficiencies in the design ofstdio. Among its features is the possibility to insertcallback functions into a stream to customize the handling of data read from or written to the stream.[7] It was released to the outside world in 1997, and the last release was 1 February 2005.[8]

See also

[edit]

References

[edit]
  1. ^ISO/IEC 9899:1999 specification. p. 274, § 7.19.
  2. ^Kernighan, Brian;Pike, Rob (1984).The UNIX Programming Environment.Englewood Cliffs:Prentice Hall. p. 200.Bibcode:1984upe..book.....K.
  3. ^McIlroy, M. D. (1987).A Research Unix reader: annotated excerpts from the Programmer's Manual, 1971–1986(PDF) (Technical report). CSTR. Bell Labs. 139.
  4. ^"(stdio.h) - C++ Reference".C++. Retrieved25 July 2021.
  5. ^stdio.h – Base Definitions Reference,The Single UNIX Specification, Version 4 fromThe Open Group
  6. ^"Sfio: A Safe/Fast I/O Library". Archived from the original on 11 February 2006. Retrieved16 March 2021.{{cite web}}: CS1 maint: bot: original URL status unknown (link)
  7. ^Korn, David G.; Vo, Kiem-Phong (1991).SFIO: Safe/Fast String/File IO. Proc. Summer USENIX Conf.CiteSeerX 10.1.1.51.6574.
  8. ^Fowler, Glenn S.; Korn, David G.; Vo, Kiem-Phong (2000).Extended Formatting with Sfio. Proc. Summer USENIX Conf.

External links

[edit]
The WikibookC Programming has a page on the topic of:C Programming/C Reference
Features
Standard library
Implementations
Compilers
IDEs
Comparison with
other languages
Descendant
languages
Designer
Retrieved from "https://en.wikipedia.org/w/index.php?title=C_file_input/output&oldid=1271431638#fopen"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp