Content deleted Content added
merged fopen and fclose |
formatting |
||
Line 1:
In [[C (programming language)|C programming]], [[File system|file]] [[input/output|input and output]] is
#A file is opened for reading/writing/appending, using <code>fopen</code>;
#The file is processed;
#The file is closed, using <code>fclose</code>.
==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 0. 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.
They are defined as
Line 20:
!colspan=3| mode || description || starts..
|-
|<tt>r</tt> || <tt>rb</tt> || || open for reading || beginning
|-
|<tt>w</tt> || <tt>wb</tt> || || open for writing (creates file if it doesn't exist). Deletes content and overwrites the file. || beginning
|-
|<tt>a</tt> || <tt>ab</tt> || || open for appending (creates file if it doesn't exist) || end
|-
|<tt>r+</tt> || <tt>rb+</tt> || <tt>r+b</tt> || open for reading and writing || beginning
|-
|<tt>w+</tt> || <tt>wb+</tt> || <tt>w+b</tt> || open for reading and writing. Deletes content and overwrites the file. || beginning
|-
|<tt>a+</tt> || <tt>ab+</tt> || <tt>a+b</tt> || open for reading and writing (append if file exists) || end
|}
The '<tt>b</tt>' stands for
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
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>\ /: * ? > <</tt> and <tt>|</tt> cannot be part of a file name.
==Closing a file using <tt>fclose</tt>==
:<code>int fclose(FILE *file_pointer)</code>
|