Syntax
#include <io.h> #include <fcntl.h> #include <sys\stat.h> int open(char *pathname, int oflag, int pmode);Description
open opens the file specified by pathname and prepares the file for subsequent reading or writing as defined by oflag. open can also prepare the file for reading and writing.
The oflag is an integer expression formed by combining one or more of the following constants, defined in <fcntl.h>. To specify more than one constant, join the constants with the bitwise OR operator (|); for example, O_CREAT | O_TEXT.
Oflag
If neither O_BINARY or O_TEXT is specified, the default will be O_TEXT; it is an error to specify both O_BINARY and O_TEXT. You must specify one of the access mode flags, O_RDONLY, O_WRONLY, or O_RDWR. There is no default.
Warning: Use O_TRUNC with care; it destroys the complete contents of an existing file.
For more details on text and binary modes and their differences, see "Stream Processing" in the VisualAge C++ Programming Guide.
The pmode argument is an integer expression containing one or both of the constants S_IWRITE and S_IREAD, defined in <sys\stat.h>. The pmode is required only when O_CREAT is specified. If the file exists, pmode is ignored. Otherwise, pmode specifies the permission settings for the file. These are set when the new file is closed for the first time. The meaning of the pmode argument is as follows: compact break=fit.
Value
If write permission is not given, the file is read-only. Under the OS/2 operating system, all files are readable; you cannot give write-only permission. The modes S_IWRITE and S_IREAD | S_IWRITE are equivalent.
open applies the current file permission mask to pmode before setting the permissions. (See umask.)
Note: In earlier releases of C Set ++, open began with an underscore (_open). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, The Developer's Toolkit will map _open to open for you.
open returns a file handle for the opened file. A return value of -1 indicates an error, and errno is set to one of the following values: compact break=fit.
Value
This example opens the file edopen.dat by creating it as a new file, truncating it if it exists, and opening it so it can be read and written to. The open command issued also grants permission to read from and write to the file.
#include <io.h>#include <stdio.h> #include <fcntl.h> #include <sys\stat.h> #include <stdlib.h> int main(void) { int fh; if (-1 == (fh = open("edopen.dat", O_CREAT|O_TRUNC|O_RDWR, S_IREAD|S_IWRITE))) { perror("Unable to open edopen.dat"); return EXIT_FAILURE; } printf("File was successfully opened.\n"); if (-1 == close(fh)) { perror("close error"); return EXIT_FAILURE; } return 0; /**************************************************************************** The output should be: File was successfully opened. ****************************************************************************/ }Related Information