C file input/output: Difference between revisions

Content deleted Content added
mNo edit summary
huge cleanup, merge from fgetc, recat
Line 1:
InThe [[C (programming language)|C programming language]], provides many [[Filestandard systemlibrary]] [[subroutine|functions]] for [[computer file|file]] [[input/output|input and output]]. isThese initiatedfunctions andmake terminated byup the bulk of the <code>'''fopen'''</code>[[C andstandard <code>'''fclose'''</code>library]] [[Subroutineheader file|functionsheader]], respectively, which are defined in the <code><[[stdio.h]] [[C standard library]]></code>. Typically, they are used in a sequence:
#A file is opened for reading/writing/appending, using <code>fopen</code>;
#The file is processed;
#The file is closed, using <code>fclose</code>.
 
The I/O functionality of C is fairly low-level by modern standards; C abstracts all file operations into operations on [[stream (computer)|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]] 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.
==Opening a file using <tt>fopen</tt>==
 
A file is opened using <code>'''fopen'''</code>, which returns an I/O [[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. Because the functionality is so useful, many languages derived from C provide functions of the same name, with the same or similar function: for example, [[PHP]]. <code>fopen</code> is considered higher-level than the <code>open</code> [[system call]] of UNIX operating systems. The related C library function '''<code>freopen</code>''' performs the same operation after first closing any open stream associated with its parameter.
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]].
 
==Opening a file using <tt>fopen</tt>==
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]].
 
The related C library function <code>'''freopen'''</code> performs the same operation after first closing any open stream associated with its parameter.
 
They are defined as
:<code>FILE *fopen(const char *path, const char *mode);</code>
:<code>FILE *fdopenfreopen(intconst fildeschar *path, const char *mode, FILE *fp);</code>
:<code>FILE *freopen(const char *path, const char *mode, FILE *stream);</code>
 
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.
The '''<code>fdopen</code>''' function is not standard in C89 or C99, but is an extension used in [[POSIX]] environments and imitated elsewhere.
 
The '''<code>mode'''</code> parameter isto <code>fopen</code> and <code>freopen</code> must be a [[C string|string]] that begins with one of the following sequences:
 
{| class="wikitable"
Line 33 ⟶ 35:
|}
 
The '"<tt>b</tt>'" stands for '''b'''inary. The C standard givesprovides for two kinds of files &mdash; [[text file]]s and [[binary file]]s &mdash; although operating systems mayare ornot mayrequired notto 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 linefeed character; in the [[Appleline Macintosh|Macintoshfeed]] OS, a bare carriage returncharacter; on [[DOS]] andin [[Microsoft Windows]], a [[carriage return]] followed by a linefeedline 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.
 
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]
 
Writing and appending modes will attempt to create a file to write to inof the case that the filegiven name doesn't already exist. However, the operation of fopen is undefined if theno filenamesuch doesn'tfile followalready requirementsexists. byAs the OS. Formentioned exampleabove, if thethis filename contains illegal charactersoperation fails, the program might crash. For example, in windows <ttcode>\ /: * ? &gt; &lt;fopen</ttcode> andwill return <ttcode>|[[NULL]]</ttcode> cannot be part of a file name.
 
==Closing a filestream using <tt>fclose</tt>==
ItThe <code>fclose</code> function takes one argument: a [[pointer]] to the ''<code>FILE''</code> structure of the stream to close, eg:.
 
:<code>int fclose(FILE *file_pointerfp);</code>
 
The function returns [[zero]] on success, or [[end-of-file|EOF]] on failure.
It takes one argument: a pointer to the ''FILE'' structure of the stream to close, eg:
<code>:fclose(''my_file_pointer'')</code>
This line call the function fclose to close ''FILE'' stream structure pointed by ''my_file_pointer''.
 
==Reading from a stream using fgetc==
The return value is an integer with the following meaning:
The <code>'''fgetc'''</code> function is used to read a character from a stream.
* ''0'' (zero): the stream was closed successfully;
* ''EOF'': an error occurred;
 
:<code>int fgetc(FILE *fp);</code>
One can check for an error by reading [[errno]]. fclose has undefined behavior if it attempts to close a file pointer that isn't currently assigned to a file - in many cases, this results in a program crash.
 
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.)
==Example usage==
 
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.
The following program opens a file called ''myfile.txt'', scans for an integer in it, then closes the file.
<pre>
#include <stdio.h>
 
The standard function <code>'''getchar'''</code>, also defined in <code><stdio.h></code>, takes no arguments, and is equivalent to <code>fgetc([[stdin]])</code>.
 
==Writing to a stream using fputc==
The <code>'''fputc'''</code> function is used to write a character to a stream.
 
:<code>int fputc(int c, FILE *fp);</code>
 
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>.
 
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.txtdat'', scansreads forfive anbytes integer infrom it, and then closes the file.
<code>
[[#include]] <stdio.h>
int main(void)
{
char buffer[5] = {0}; /* initialized to zeros */
FILE *file_pointer;
int i;
file_pointer FILE *fp = fopen("myfile.txtdat", "rwb");
if (fp == NULL) {
file_pointer = fopen("myfile.txt", "r");
[[printf]]("The integerfile isdidn't %dopen.\n", i);
fscanf(file_pointer, "%d", &i);
return 0;
printf("The integer is %d\n", i);
}
fclose(file_pointer);
for (i=0; i < 5; ++i) {
int rc = fgetc(fp);
return 0;
if (rc == EOF) {
printf("There was an error reading the file.\n");
break;
}
buffer[i] = rc;
}
fclose(file_pointerfp);
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;
}
</precode>
 
==See also==
*<code>[[printf]]</code>
*[http://www.gamedev.net/reference/articles/article1127.asp Gamedev's article on C++ file IO] - this includes ways of handling binary files.
 
==External links==
*[http://www.gamedev.net/reference/articles/article1127.asp Gamedev's article on C++ file IOI/O], - this includesincluding ways of handling binary files.
*{{man|3|fclose}}
*{{man|3|fgetc}}
*{{man|3|fopen}}
*{{man|3|fputc}}
 
[[Category:stdio.h]]
[[Category:Input/Output]]
[[Category:Articles with example C code]]
 
[[ja:Fgetc]]