Content deleted Content added
m moved Fopen to C file input/output: merging fopen and fclose |
merged fopen and fclose |
||
Line 1:
In [[C (programming language)|C programming]], [[File system|file]] [[input/output|input and output]] is controlled by the the <code>'''fopen'''</code> and <code>'''fclose'''</code> [[Subroutine|functions]], respectively, which are defined in the [[stdio.h]] [[C standard library]]. 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>.
==<tt>fopen</tt>==
They are defined as
Line 34 ⟶ 37:
When a file is opened with update mode ( '+' 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 fflush() or to a file positioning function ( [[Fseek|fseek()]], fsetpos(), or [[Rewind (C)|rewind()]]), 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 create a file to write to in the case that the file name doesn't already exist. However, the operation of fopen is undefined if the filename doesn't follow requirements by the OS. For example, if the filename contains illegal characters , the program might crash. For example, in windows <tt>\ /: * ?
:<code>int fclose(FILE *file_pointer)</code>
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''.
The return value is an integer with the following meaning:
* ''0'' (zero): the stream was closed successfully;
* ''EOF'': an error occurred;
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.
==Example usage==
The following program opens a file called ''myfile.txt'', scans for an integer in it, then closes the file.
<pre>
#include <stdio.h>
int main(void)
{
int i;
FILE *f = fopen("filename", "r");▼
fscanf(file_pointer, "%d", &i);
printf("The integer is %d\n", i);
return 0;
Line 56 ⟶ 75:
==See also==
*[http://www.gamedev.net/reference/articles/article1127.asp Gamedev's article on C++ file IO] - this includes ways of handling binary files.
▲* <tt>[[fclose]]</tt>
[[Category:stdio.h]]
|