Header File
io.h, fcntl.h
Category
Input/output Routines
Prototype
int open(const char *path, int access [, unsigned mode]);
int _wopen(const wchar_t *path, int access [, unsigned mode]);
Description
Opens a file for reading or writing.
open opens the file specified by path, then prepares it for reading and/or writing as determined by the value of access.
To create a file in a particular mode, you can either assign to the global variable _fmode or call open with the O_CREAT and O_TRUNC options ORed with the translation mode desired.
open("XMP",O_CREAT|O_TRUNC|O_BINARY,S_IREAD)
creates a binary-mode, read-only file named XMP, truncating its length to 0 bytes if it already existed.
For open, access is constructed by bitwise ORing flags from the following lists. Only one flag from the first list can be used (and one must be used); the remaining flags can be used in any logical combination.
These symbolic constants are defined in fcntl.h.
O_RDONLY |
Open for reading only. |
O_WRONLY |
Open for writing only. |
O_RDWR |
Open for reading and writing. |
O_NDELAY |
Not used; for UNIX compatibility. |
O_APPEND |
If set, the file pointer will be set to the end of the file prior to each write. |
O_CREAT |
If the file exists, this flag has no effect. If the file does not exist, the file is created, and the bits of mode are used to set the file attribute bits as in chmod. |
O_TRUNC |
If the file exists, its length is truncated to 0. The file attributes remain unchanged. |
O_EXCL |
Used only with O_CREAT. If the file already exists, an error is returned. |
O_BINARY |
Can be given to explicitly open the file in binary mode. |
O_TEXT |
Can be given to explicitly open the file in text mode. |
If neither O_BINARY nor O_TEXT is given, the file is opened in the translation mode set by the global variable _fmode.
If the O_CREAT flag is used in constructing access, you need to supply the mode argument to open from the following symbolic constants defined in sys\stat.h.
S_IWRITE |
Permission to write |
S_IREAD |
Permission to read |
S_IREAD|S_IWRITE |
Permission to read and write |
Return Value
On success, open returns a nonnegative integer (the file handle). The file pointer, which marks the current position in the file, is set to the beginning of the file.
On error, open returns -1 and the global variable errno is set to one of the following values:
EACCES |
Permission denied |
EINVACC |
Invalid access code |
EMFILE |
Too many open files |
ENOENT |
No such file or directory |
Example
#include <string.h> #include <stdio.h> #include <fcntl.h> #include <io.h> int main(void) { int handle; char msg[] = "Hello world"; if ((handle = open("TEST.$$$", O_CREAT | O_TEXT)) == -1) { perror("Error:"); return 1; } write(handle, msg, strlen(msg)); close(handle); return 0; }
Portability
|
POSIX |
Win32 |
ANSI C |
ANSI C++ |
open |
+ |
+ |
|
|
_wopen |
|
NT only |
|
|
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
|
What do you think about this topic? Send feedback!
|