======
IO.H
======
Includes
========
STDARG.H
Functions
=========
access
chmod
_chmod
chsize
close
_close
creat
_creat
creatnew
creattemp
dup
dup2
eof
filelength
getftime
ioctl
isatty
lock
locking
lseek
mktemp
open
_open
read
_read
remove
rename
setftime
setmode
sopen
tell
umask
unlink
unlock
write
_write
Constants, data types, and global variables
===========================================
ftime structure
HANDLE_MAX
fseek/lseek modes
See Also
========
List of all Header files
SEEK_xxx <IO.H, STDIO.H>
==========
#defines that set seek starting points
Constant |Value| File location
----------+-----+------------------------------
SEEK_SET | 0 | Seeks from beginning of file
SEEK_CUR | 1 | Seeks from current position
SEEK_END | 2 | Seeks from end of file
See Also:
fseek
lseek
HANDLE_MAX <IO.H>
============
Maximum number of handles.
ftime <IO.H>
=======
A file's time and date. Used by the functions
getftime and setftime.
struct ftime {
unsigned ft_tsec : 5; /* Two seconds */
unsigned ft_min : 6; /* Minutes */
unsigned ft_hour : 5; /* Hours */
unsigned ft_day : 5; /* Days */
unsigned ft_month : 4; /* Months */
unsigned ft_year : 7; /* Year - 1980 */
};
ft_hour ft_min ft_tsec
15.....11 10........5 4.......0
|-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Hours Minutes Seconds/2
ft_year ft_month ft_day
31.........25 24...21 20.....16
|-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Year - 1980 Month Day
_openfd <IO.H>
=========
The array of access modes for files and
devices.
Declaration: extern unsigned int _openfd[]
See Also:
List of all global variables
tzname <IO.H>
=========
Array of pointers to strings
Declaration: extern char * tzname[2]
An array of pointers to strings containing
abbreviations for time-zone names.
tzname[0] points to a three-character string
with the value of the time zone name from the
TZ environment string.
tzname[1] points to a three-character string
with the value of the daylight saving
time zone name from the TZ environment
string.
If no daylight saving name is present,
tzname[1] points to a null string.
See Also:
List of all global variables
========
access <IO.H>
========
Determines accessibility of a file
Declaration: int access(const char *filename, int amode);
Remarks:
access checks the file named by filename to
determine if it exists, and whether it can
be read, written to, or executed.
These are possible amode values:
Value | Description
------+-------------------------------------
06 | Check for read and write permission
04 | Check for read permission
02 | Check for write permission
01 | Execute (ignored)
00 | Check for existence of file
Under DOS, all existing files have read
access (amode = 04), so 00 and 04 give the
same result.
amode values of 06 and 02 are equivalent
because, under DOS, write access implies read
access.
If filename refers to a directory, access
simply determines whether the directory
exists.
Return Value:
* On success (the requested access is allowed), returns 0.
* Otherwise, returns -1 and sets errno to one of the following:
ENOENT Path or file name not found
EACCES Permission denied
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
See Also:
chmod
fstat
stat
Example:
#include <stdio.h>
#include <io.h>
int file_exists(char *filename);
int main(void)
{
printf("Does NOTEXIST.FIL exist: %s\n",
file_exists("NOTEXISTS.FIL") ? "YES" : "NO");
return 0;
}
int file_exists(char *filename)
{
return (access(filename, 0) == 0);
}
=======
chmod <IO.H>
=======
Sets file access permissions
Declaration: int chmod(const char *path, int amode);
Remarks:
chmod sets the file-access permissions of the
file given by *path.
Argument | What It Is/Does
----------+----------------------------------------------------------------
path | Points to a string that names the file whose attributes are
| set; *path = first character of that string
amode | Contains one or both of 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, returns 0
* Otherwise, returns -1 and sets errno to
one of the following:
* ENOENT (Path or file name not found)
* EACCES (Permission denied)
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
See Also:
access
_chmod
fstat
open
sopen
stat
Example:
/* NEW chmod() example: */
#include <errno.h>
#include <stdio.h>
#include <io.h>
#include <process.h>
#include <sys\stat.h>
/*
COMMENT FROM KMc:
Isn't main() supposed to be declared as
"int main(void)" rather than "void main(void)"?
*/
void main(void)
{
char filename[64];
struct stat stbuf;
int amode;
printf("Enter name of file: ");
scanf("%s", filename);
if (stat(filename, &stbuf) != 0)
{
perror("Unable to get file information");
exit(1);
}
if (stbuf.st_mode & S_IWRITE)
{
printf("Changing to read-only\n");
amode = S_IREAD;
}
else
{
printf("Changing to read-write\n");
amode = S_IREAD|S_IWRITE;
}
if (chmod(filename, amode) != 0)
{
perror("Unable to change file mode");
exit(1);
}
exit(0);
}
====================================
_chmod, <IO.H>
_dos_getfileattr, _dos_setfileattr <DOS.H>
====================================
Gets or sets file attributes
Declaration:
* int _chmod(const char *path, int func [ , int attrib ] );
* int _dos_getfileattr(const char *path, unsigned *attribp);
* int _dos_setfileattr(const char *path, unsigned attrib);
Remarks:
These functions get and/or set the DOS file
attributes of the file given by *path:
* _chmod gets or sets the attributes
* _dos_getfileattr gets the attributes
* _dos_setfileattr sets the attributes
Argument | What It Is/Does
----------+----------------------------------------------------------------
path | Points to a string that names the file whose attributes are
| fetched or set; *path = first character of that string
func | Specifies whether _chmod gets or sets attributes of the file
| *path:
| * If func = 0, _chmod returns the current DOS attributes
| * If func = 1, _chmod sets the attributes to attrib
attrib | One of the DOS file-attribute symbolic constants defined
| in DOS.H.
attribp | Points to location where _dos_getfileattr stores attributes
Return Value:
* On success,
* _chmod returns file attribute word
* _dos_getfileattr and _dos_setfileattr return 0
* On error,
* _chmod returns -1 and sets errno to one of the following:
ENOENT (Path or file name not found)
EACCES (Permission denied)
* _dos_getfileattr returns the DOS error code and sets errno to
ENOENT or EACCES
* _dos_setfileattr returns the DOS error code and sets errno to
ENOENT
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | | |
+-----+------+---------+--------+----------+
See Also:
chmod
_creat
stat
Examples:
_chmod example
_dos_getfileattr example
_dos_setfileattr example
_chmod example
================
#include <errno.h>
#include <stdio.h>
#include <dos.h>
#include <io.h>
int get_file_attrib(char *filename);
int main(void)
{
char filename[128];
int attrib;
printf("Enter a filename:");
scanf("%s", filename);
attrib = get_file_attrib(filename);
if (attrib == -1)
switch(errno)
{
case ENOENT : printf("Path or file not found.\n");
break;
case EACCES : printf("Permission denied.\n");
break;
default: printf("Error number: %d", errno);
break;
}
else
{
if (attrib & FA_RDONLY)
printf("%s is read-only.\n", filename);
if (attrib & FA_HIDDEN)
printf("%s is hidden.\n", filename);
if (attrib & FA_SYSTEM)
printf("%s is a system file.\n", filename);
if (attrib & FA_LABEL)
printf("%s is a volume label.\n", filename);
if (attrib & FA_DIREC)
printf("%s is a directory.\n", filename);
if (attrib & FA_ARCH)
printf("%s is an archive file.\n", filename);
}
return 0;
}
/* returns the attributes of a DOS file */
int get_file_attrib(char *filename)
{
return(_chmod(filename, 0));
}
_dos_getfileattr example
==========================
#include <stdio.h>
#include <dos.h>
int main(void)
{
char filename[128];
unsigned attrib;
printf("Enter a file name:");
scanf("%s", filename);
if (_dos_getfileattr(filename,&attrib) != 0)
{
perror("Unable to obtain file attributes");
return 1;
}
if (attrib & _A_RDONLY)
printf("%s is read-only.\n", filename);
if (attrib & _A_HIDDEN)
printf("%s is hidden.\n", filename);
if (attrib & _A_SYSTEM)
printf("%s is a system file.\n", filename);
if (attrib & _A_VOLID)
printf("%s is a volume label.\n", filename);
if (attrib & _A_SUBDIR)
printf("%s is a directory.\n", filename);
if (attrib & _A_ARCH)
printf("%s is an archive file.\n", filename);
return 0;
}
_dos_setfileattr example
==========================
#include <stdio.h>
#include <dos.h>
int main(void)
{
char filename[128];
unsigned attrib;
printf("Enter a file name:");
scanf("%s", filename);
if (_dos_getfileattr(filename,&attrib) != 0)
{
perror("Unable to obtain file attributes");
return 1;
}
if (attrib & _A_RDONLY)
{
printf("%s currently read-only, making it read-write.\n", filename);
attrib &= ~_A_RDONLY;
}
else
{
printf("%s currently read-write, making it read-only.\n", filename);
attrib |= _A_RDONLY;
}
if (_dos_setfileattr(filename,attrib) != 0)
perror("Unable to set file attributes");
return 0;
}
========
chsize <IO.H>
========
Changes file size
Declaration: int chsize(int handle, long size);
Remarks:
chsize changes the size of the file
associated with handle.
chsize can truncate or extend the file,
depending on the value of size compared
to the file's original size.
* If chsize extends the file, it will append
null characters (\0).
* If chsize truncates the file, all data
beyond the new end-of-file indicator is
lost.
The mode in which you open the file must
allow writing.
Return Value:
* On success, returns 0.
* On failure, returns -1, and sets errno to
one of the following:
EACCESS (Permission denied)
EBADF (Bad file number)
ENOSPC (UNIX--not DOS)
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | | |
+-----+------+---------+--------+----------+
See Also:
_creat
close
creat
open
Example:
#include <string.h>
#include <fcntl.h>
#include <io.h>
int main(void)
{
int handle;
char buf[11] = "0123456789";
/* create text file containing 10 bytes */
handle = open("DUMMY.FIL", O_CREAT);
write(handle, buf, strlen(buf));
/* truncate the file to 5 bytes in size */
chsize(handle, 5);
/* close the file */
close(handle);
return 0;
}
================
close, _close, <IO.H>
and _dos_close <DOS.H>
================
Closes a file associated with a handle
Declaration:
* int close(int handle);
* int _close(int handle);
* unsigned _dos_close(int handle);
Remarks:
Each of these functions closes the file
associated with handle.
Argument| Function | What Argument Is
--------+------------+----------------------------------------------------
handle | close and | File handle obtained from a call to creat, _creat,
| _close | creatnew, creattemp, dup, dup2, open, or _open
| |
handle | _dos_close | File handle obtained from a call to _dos_creat,
| | _dos_creatnew, or _dos_open
close and _close do not write a Ctrl-Z
character at the end of the file.
To terminate the file with a Ctrl-Z, you must
explicitly output one.
Return Value:
* On success, these functions return 0
* On error (handle is not the handle of a valid, open file),
* close and _close return -1 and set errno to EBADF (Bad file number)
* _dos_close returns the DOS error code and sets errno to EBADF
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
_close | Yes | | Yes | | |
close | Yes | Yes | Yes | | |
_dos_close | Yes | | Yes | | |
+-----+------+---------+--------+----------+
See Also:
chsize
creat/_creat
creatnew
creattemp
_dos_creat
_dos_creatnew
_dos_open
_dos_read
_dos_write
dup/dup2
fclose
_open
open
read
sopen
write
Examples:
close example
_close example
_dos_close example
close example
===============
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
main()
{
int handle;
char buf[11] = "0123456789";
/* create a file containing 10 bytes */
handle = open("NEW.FIL", O_CREAT);
if (handle > -1)
{
write(handle, buf, strlen(buf));
close(handle); /* close the file */
}
else
{
printf("Error opening file\n");
}
return 0;
}
_close 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_RDWR)) == -1)
{
perror("Error:");
return 1;
}
_write(handle, msg, strlen(msg));
_close(handle);
return 0;
}
_dos_close example
====================
#include <dos.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
unsigned count;
int handle;
char buf[11] = "0123456789";
/* create a file containing 10 bytes */
if (_dos_creat("DUMMY.FIL", _A_NORMAL, &handle) != 0)
{
perror("Unable to create DUMMY.FIL");
return 1;
}
if (_dos_write(handle, buf, strlen(buf), &count) != 0)
{
perror("Unable to write to DUMMY.FIL");
return 1;
}
/* close the file */
_dos_close(handle);
return 0;
}
================
creat, _creat, <IO.H>
and _dos_creat <DOS.H>
================
Create a new file or overwrite an existing one
Declaration:
* int creat(const char *path, int amode);
* int _creat(const char *path, int attrib);
* unsigned _dos_creat(const char *path, int attrib, int *handlep);
Remarks:
creat and _create both create a new file (or
prepare to rewrite an existing file) given by
path.
_dos_creat uses DOS function 0x3C to create
and open the file given by path.
Argument | Function | What Argument Is/Does
----------+------------+--------------------------------------------------
amode | creat | Access-mode word; applies only to newly created
| | files. Can be one of the following constants
| | defined in SYS\STAT.H:
| | * S_IWRITE (Permission to write)
| | * S_IREAD (Permission to read)
| | * S_IREAD|S_IWRITE (Permission to read/write)
| | creat examines only the S_IWRITE bit of amode.
| | * If S_IWRITE = 1, new file can be written to
| | * If S_IWRITE = 0, new file marked as read-only
| | All other DOS attributes are set to 0.
| |
attrib | _creat | Access permission (a DOS attribute word) given
| _dos_creat | to the new file. Can be one of the following
| | constants defined in DOS.H:
| | * FA_RDONLY Read-only attribute
| | * FA_HIDDEN Hidden file
| | * FA_SYSTEM System file
| |
handlep | _dos_creat | Pointer to location where the new file's handle
| | is stored
| |
path | (all) | Name of the file to be created or overwritten
In DOS, write permission implies read
permission.
The file is always opened in binary mode, for
both reading and writing.
Upon successful file creation, the file
pointer is set to the beginning of the file.
If the file already exists, its size is reset
to 0. (This is essentially the same as
deleting the file and creating a new file
with the same name.)
creat only
==========
If the write attribute of the existing file
is set, creat truncates the file to a length
of 0 bytes, leaving the file attributes
unchanged.
If the read-only attribute of the existing
file is set, the creat call fails and the
file remains unchanged.
A file created with creat is always created
in the translation mode specified by the
global variable _fmode (O_TEXT or O_BINARY).
Return Value:
* On success,
* creat and _creat return the new file handle, a non-negative integer
* _dos_creat returns 0
* On error,
* creat and _creat return -1 and set errno to one of the following:
ENOENT (Path or file name not found)
EMFILE (Too many open files)
EACCES (Permission denied)
* _dos_creat returns the DOS error code and sets errno to EMFILE,
EACCES, or ENOMEM (Not enough memory).
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
creat | Yes | Yes | Yes | | |
_creat | Yes | | Yes | | |
_dos_creat | Yes | | Yes | | |
+-----+------+---------+--------+----------+
See Also:
chmod/_chmod
chsize
close/_close
creatnew
creattemp
_dos_close
_dos_creatnew
_dos_getfileattr
_dos_setfileattr
dup/dup2
fopen
open
sopen
write
Examples:
creat example
_creat example
_dos_creat example
creat example
===============
#include <sys\stat.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
int main(void)
{
int handle;
char buf[11] = "0123456789";
/* change the default file mode from text to binary */
_fmode = O_BINARY;
/* create a binary file for reading and writing */
handle = creat("DUMMY.FIL", S_IREAD |S_IWRITE);
/* write 10 bytes to the file */
write(handle, buf, strlen(buf));
/* close the file */
close(handle);
return 0;
}
_creat example
================
#include <dos.h>
#include <string.h>
#include <stdio.h>
#include <io.h>
int main() {
unsigned count;
int handle;
char buf[11] = "0123456789";
/* Create a 10-byte file using _dos_creat. */
if (_dos_creat("DUMMY.FIL", _A_NORMAL, &handle) != 0) {
perror("Unable to _dos_creat DUMMY.FIL");
return 1;
}
if (_dos_write(handle, buf, strlen(buf), &count) != 0) {
perror("Unable to _dos_write to DUMMY.FIL");
return 1;
}
_dos_close(handle);
/* Create another 10-byte file using _creat. */
if ((handle = _creat("DUMMY2.FIL", 0)) < 0) {
perror("Unable to _create DUMMY2.FIL");
return 1;
}
if (_write(handle, buf, strlen(buf)) < 0) {
perror("Unable to _write to DUMMY2.FIL");
return 1;
}
_close(handle);
return 0;
_dos_creat example
====================
#include <dos.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
unsigned count;
int handle;
char buf[11] = "0123456789";
/* create a file containing 10 bytes */
if (_dos_creat("DUMMY.FIL", _A_NORMAL, &handle) != 0)
{
perror("Unable to create DUMMY.FIL");
return 1;
}
if (_dos_write(handle, buf, strlen(buf), &count) != 0)
{
perror("Unable to write to DUMMY.FIL");
return 1;
}
/* close the file */
_dos_close(handle);
return 0;
}
===============
creatnew <IO.H>
_dos_creatnew <DOS.H>
===============
Creates and opens a new file for reading and writing in binary mode
Declaration:
* int creatnew(const char *path, int mode);
* unsigned _dos_creatnew(const char *path, int attrib, int *handlep);
Remarks:
_dos_creatnew and creatnew use DOS function
0x5B to create and open the new file given
by path. If the file exists, these functions
return an error and leave the file untouched.
Argument | Function | What Argument Is/Does
---------+---------------+-----------------------------------------------
path | (both) | Name of the file to be created
| |
mode | creatnew | Access permission (a DOS attribute word). Can
attrib | _dos_creatnew | be one of the following constants defined in
| | DOS.H:
| | * FA_RDONLY Read-only attribute
| | * FA_HIDDEN Hidden file
| | * FA_SYSTEM System file
| |
handlep | _dos_creatnew | Points to location where the new file's handle
| | is stored
Upon successful file creation, _dos_creatnew
sets the file pointer to the beginning of the
file.
Return Value:
* On success,
* creatnew returns the new file handle, a non-negative integer
* _dos_creatnew returns 0
* On error,
* creatnew returns -1 and sets errno to one of the following:
EEXIST (File already exists)
ENOENT (Path or file name not found)
EMFILE (Too many open files)
EACCES (Permission denied)
* _dos_creatnew returns the DOS error code and sets errno to
EEXIST, ENOENT, EMFILE, or EACCES
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | | |
+-----+------+---------+--------+----------+
See Also:
close
creat/_creat
creattemp
_dos_close
_dos_creat
_dos_getfileattr
_dos_setfileattr
dup
_fmode
open
Examples:
_dos_creatnew example
creatnew example
_dos_creatnew example
=======================
#include <dos.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
unsigned count;
int handle;
char buf[11] = "0123456789";
/* create a file containing 10 bytes */
if (_dos_creatnew("DUMMY.FIL", _A_NORMAL, &handle) != 0)
{
perror("Unable to create DUMMY.FIL");
return 1;
}
if (_dos_write(handle, buf, strlen(buf), &count) != 0)
{
perror("Unable to write to DUMMY.FIL");
return 1;
}
/* close the file */
_dos_close(handle);
return 0;
}
creatnew example
==================
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <dos.h>
#include <io.h>
int main(void)
{
int handle;
char buf[11] = "0123456789";
/* attempt to create a file that doesn't already exist */
handle = creatnew("DUMMY.FIL", 0);
if (handle == -1)
printf("DUMMY.FIL already exists.\n");
else
{
printf("DUMMY.FIL successfully created.\n");
write(handle, buf, strlen(buf));
close(handle);
}
return 0;
}
===========
creattemp <IO.H>
===========
Creates a unique file in the directory given by path
Declaration: int creattemp(char *path, int attrib);
Remarks:
A file created with creattemp is always
created in the translation mode specified by
_fmode (O_TEXT or O_BINARY).
Argument| What It Is/Does
--------+-----------------------------------------------------------
path | Path name ending with a backslash (\)
attrib | Can be one of the following constants defined in DOS.H:
| * FA_RDONLY Read-only attribute
| * FA_HIDDEN Hidden file
| * FA_SYSTEM System file
The file is opened for both reading and
writing. The file is always opened in binary
mode.
creattemp selects a unique file name in the
directory named by path, and stores the newly
created file name in the path string
supplied.
path should be long enough to hold the
resulting file name.
Upon successful file creation, the file
pointer is set to the beginning of the file.
The file is not automatically deleted when
the program terminates.
Return Value:
* On success, returns the new file handle,
a non-negative integer
* Otherwise, returns -1 and sets errno to one of these:
ENOENT (Path or file name not found)
EMFILE (Too many open files)
EACCES (Permission denied)
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | | |
+-----+------+---------+--------+----------+
See Also:
close
creat/_creat
creatnew
dup
open
Example:
#include <string.h>
#include <stdio.h>
#include <io.h>
int main(void)
{
int handle;
char pathname[128];
strcpy(pathname, "\\");
/* create a unique file in the root directory */
handle = creattemp(pathname, 0);
printf("%s was the unique file created.\n", pathname);
close(handle);
return 0;
}
===========
dup, dup2 <IO.H>
===========
* dup duplicates a file handle
* dup2 duplicates a file handle onto an existing file handle
Declaration:
* int dup(int handle);
* int dup2(int oldhandle, int newhandle);
Remarks:
dup creates a new file handle with the value
handle.
dup2 creates a new handle with the value
newhandle.
Argument | What It Is
-----------+--------------------------------
handle | File handle obtained from call
| to _creat, creat, _open, open,
| dup, or dup2.
-----------+--------------------------------
newhandle | File handles obtained from call
oldhandle | to creat, open, dup, or dup2.
The new file handle has the following in
common with the original file handle:
* same open file or device
* same file pointer (changing the file
pointer of one changes the other)
* same access mode: read, write, read/write
If the file associated with newhandle is open
when dup2 is called, the file is closed.
Return Value:
* On success,
* dup returns the new file handle, a
non-negative integer
* dup2 returns 0
* On error, both functions return -1 and
set errno to one of these:
* EMFILE (Too many open files)
* EBADF (Bad file number)
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
See Also:
close/_close
creat/_creat
creatnew
creattemp
fopen
_open
open
Examples:
dup example
dup2 example
dup example
=============
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
void flush(FILE *stream);
int main(void)
{
FILE *fp;
char msg[] = "This is a test";
/* create a file */
fp = fopen("DUMMY.FIL", "w");
/* write some data to the file */
fwrite(msg, strlen(msg), 1, fp);
clrscr();
printf("Press any key to flush DUMMY.FIL:");
getch();
/* flush the data to DUMMY.FIL without closing it */
flush(fp);
printf("\nFile was flushed, Press any key to quit:");
getch();
return 0;
}
void flush(FILE *stream)
{
int duphandle;
/* flush TC's internal buffer */
fflush(stream);
/* make a duplicate file handle */
duphandle = dup(fileno(stream));
/* close the duplicate handle to flush the DOS buffer */
close(duphandle);
}
dup2 example
==============
#include <sys\stat.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
int main(void)
{
#define STDOUT 1
int nul, oldstdout;
char msg[] = "This is a test";
/* create a file */
nul = open("DUMMY.FIL", O_CREAT | O_RDWR,
S_IREAD | S_IWRITE);
/* create a duplicate handle for standard output */
oldstdout = dup(STDOUT);
/*
redirect standard output to DUMMY.FIL
by duplicating the file handle onto
the file handle for standard output.
*/
dup2(nul, STDOUT);
/* close the handle for DUMMY.FIL */
close(nul);
/* will be redirected into DUMMY.FIL */
write(STDOUT, msg, strlen(msg));
/* restore original standard output handle */
dup2(oldstdout, STDOUT);
/* close duplicate handle for STDOUT */
close(oldstdout);
return 0;
}
=====
eof <IO.H>
=====
Checks for end-of-file
Declaration: int eof(int handle);
Remarks:
eof determines whether the file associated
with handle has reached end-of-file.
Return Value:
* On success (if the current position is
end-of-file), returns 1.
* Otherwise, returns 0.
* On error, returns -1 and sets errno to
EBADF (bad file number).
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | | |
+-----+------+---------+--------+----------+
See Also:
clearerr
feof
ferror
perror
Example:
#include <sys\stat.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
int main(void)
{
int handle;
char msg[] = "This is a test";
char ch;
/* create a file */
handle = open("DUMMY.FIL",
O_CREAT | O_RDWR,
S_IREAD | S_IWRITE);
/* write some data to the file */
write(handle, msg, strlen(msg));
/* seek to the beginning of the file */
lseek(handle, 0L, SEEK_SET);
/* reads chars from the file until it reaches EOF */
do
{
read(handle, &ch, 1);
printf("%c", ch);
} while (!eof(handle));
close(handle);
return 0;
}
============
filelength <IO.H>
============
Gets file size in bytes
Declaration: long filelength(int handle);
Remarks:
filelength returns the length (in bytes) of
the file associated with handle.
Return Value
* On success, returns a long value, the
file length in bytes.
* On error, returns -1 and sets errno to
EBADF (bad file number).
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | | |
+-----+------+---------+--------+----------+
See Also:
fopen
lseek
open
Example:
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
int main(void)
{
int handle;
char buf[11] = "0123456789";
/* create a file containing 10 bytes */
handle = open("DUMMY.FIL", O_CREAT);
write(handle, buf, strlen(buf));
/* display the size of the file */
printf("file length in bytes: %ld\n", filelength(handle));
/* close the file */
close(handle);
return 0;
}
=======
ioctl <IO.H>
=======
Controls I/O device
Declaration:
int ioctl(int handle, int func [ , void *argdx, int argcx ] );
Remarks:
ioctl is a direct interface to the DOS call
0x44 (IOCTL).
The arguments argdx and argcx are optional.
The exact function depends on the value of
func:
func |
Value | Means ioctl will...
-------+---------------------------------------------------------
0 | Get device information
1 | Set device information (in argdx)
2 | Read argcx bytes into the address *argdx
3 | Write argcx bytes from the address *argdx
4 | Same as 2, except handle is treated as a drive number
| (0 = default, 1 = A, etc.)
5 | Same as 3, except handle is a drive number
| (0 = default, 1 = A, etc.)
6 | Get input status
7 | Get output status
8 | Test removability; DOS 3.0 only
11 | Set sharing conflict retry count; DOS 3.0 only
ioctl can get information about device
channels. Regular files can also be used, but
only func values 0, 6, and 7 are defined for
them. All other calls return an EINVAL error
for files.
See the documentation for system call 0x44 in
your DOS reference manuals for detailed
information on argument or return values.
ioctl provides a direct interface to DOS
device drivers for special functions. As a
result, the exact behavior of this function
varies across different vendors' hardware and
in different devices.
Several vendors do not follow the interfaces
described here. Refer to the vendor BIOS
documentation for exact use of ioctl.
Return Value:
* On success,
If func = | Returns
-----------+----------------------------
0, 1 | The device information
| (DX of the IOCTL call)
-----------+------------------------------
2, 3, | The number of bytes actually
4, 5 | transferred
-----------+------------------------------
6, 7 | The device status
* On error, ioctl returns -1 and sets
errno to one of the following:
EINVAL Invalid argument
EBADF Bad file number
EINVDAT Invalid data
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
Example:
#include <stdio.h>
#include <dir.h>
#include <io.h>
int main(void)
{
int stat;
/* use func 8 to determine if the default drive is removable */
stat = ioctl(0, 8, 0, 0);
if (!stat)
printf("Drive %c is removable.\n", getdisk() + 'A');
else
printf("Drive %c is not removable.\n", getdisk() + 'A');
return 0;
}
========
isatty (in IO.H)
========
Checks for device type
Syntax: int isatty(int handle);
Remarks:
isatty determines whether handle is
associated with any one of the following
character devices:
* a terminal
* a console
* a printer
* a serial port
Return Value:
If the device is a character device, isatty
returns a nonzero integer. If it is not
a character device, isatty returns 0.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
Example:
#include <stdio.h>
#include <io.h>
int main(void)
{
int handle;
handle = fileno(stdprn);
if (isatty(handle))
printf("Handle %d is a device type\n", handle);
else
printf("Handle %d isn't a device type\n", handle);
return 0;
}
=======================
locking, lock, unlock <IO.H>
=======================
* locking sets or resets file-sharing locks
* lock sets file-sharing locks
* unlock releases file-sharing locks
Declaration:
* locking:
#include <io.h>
#include <sys\locking.h>
int locking(int handle, int cmd, long length);
* int lock(int handle, long offset, long length);
* int unlock(int handle, long offset, long length);
Remarks
These three functions provide an interface to
the DOS 3.x file-sharing mechanism. SHARE.EXE
must be loaded before you use the functions.
unlock removes a lock previously placed with
a call to lock.
Argument| Function | What Argument Is, Does
--------+----------+-------------------------------------------------------
handle | (all 3) | Specifies the open file to be locked or unlocked
cmd | locking | Specifies the action to be taken
| | (defined in SYS\LOCKING.H)
| | cmd value | What It Specifies
| | -----------+----------------------------------------
| | LK_LOCK, | Lock the region. If the lock is unsuc-
| | LK_RLCK | cessful, try once/second for 10 seconds
| | | before giving up.
| | LK_NBLCK, | Lock the region. If the lock if unsuc-
| | LK_NBRLCK | cessful, give up immediately.
| | LK_UNLCK | Unlock the region, which must have been
| | | previously locked.
length | (all 3) | Length (in bytes) of region to be locked or unlocked
offset | lock, | Specifies how many bytes into the file the lock or
| unlock | unlock action is to occur.
Locks can be placed on arbitrary,
non-overlapping regions of any file. The
region to be locked or unlocked starts at
the current file position.
A program attempting to read or write into a
locked region will retry the operation three
times. If all three retries fail, the call
fails with an error.
To avoid error, all locks must be removed
before a file is closed. A program must
release all locks before completing.
Portability
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | | |
+-----+------+---------+--------+----------+
Return Value
* On success, all three functions return 0
* On error, all three functions return -1
and locking sets errno to one of these:
EBADF Bad file number
EACCESS File already locked or unlocked
EDEADLOCK File cannot be locked after 10 retries
(cmd is LK_LOCK or LK_RLCK)
EINVAL Invalid cmd, or SHARE.EXE not loaded
See Also:
_fsopen
open
sopen
Examples
locking example
lock example
unlock example
locking example
=================
#include <io.h>
#include <fcntl.h>
#include <process.h>
#include <share.h>
#include <stdio.h>
#include <sys\locking.h>
int main(void)
{
int handle, status;
long length;
/* must have DOS SHARE.EXE loaded for file locking to function */
handle = sopen("c:\\autoexec.bat", O_RDONLY,SH_DENYNO);
if (handle < 0) {
printf("sopen failed\n");
exit(1);
}
length = filelength(handle);
status = locking(handle,LK_LOCK,length/2);
if (status == 0)
printf("lock succeeded\n");
else
perror("lock failed");
status = locking(handle,LK_UNLCK,length/2);
if (status == 0)
printf("unlock succeeded\n");
else
perror("unlock failed");
close(handle);
return 0;
}
lock example
==============
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>
#include <process.h>
#include <share.h>
#include <stdio.h>
int main(void)
{
int handle, status;
long length;
/* Must have DOS Share.exe loaded for */
/* file locking to function properly */
handle = sopen("c:\\autoexec.bat",
O_RDONLY,SH_DENYNO,S_IREAD);
if (handle < 0)
{
printf("sopen failed\n");
exit(1);
}
length = filelength(handle);
status = lock(handle,0L,length/2);
if (status == 0)
printf("lock succeeded\n");
else
printf("lock failed\n");
status = unlock(handle,0L,length/2);
if (status == 0)
printf("unlock succeeded\n");
else
printf("unlock failed\n");
close(handle);
return 0;
}
unlock example
================
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>
#include <process.h>
#include <share.h>
#include <stdio.h>
int main(void)
{
int handle, status;
long length;
handle = sopen("c:\\autoexec.bat",O_RDONLY,SH_DENYNO,S_IREAD);
if (handle < 0)
{
printf("sopen failed\n");
exit(1);
}
length = filelength(handle);
status = lock(handle,0L,length/2);
if (status == 0)
printf("lock succeeded\n");
else
printf("lock failed\n");
status = unlock(handle,0L,length/2);
if (status == 0)
printf("unlock succeeded\n");
else
printf("unlock failed\n");
close(handle);
return 0;
}
=======
lseek <IO.H>
=======
Moves read/write file pointer
Declaration: long lseek(int handle, long offset, int fromwhere);
Remarks:
lseek sets the file pointer associated with
handle to a new position offset bytes beyond
the file location given by fromwhere.
It is a good idea to set fromwhere using one
of the SEEK_xxx symbolic constants (defined
in IO.H).
Return Value:
* On success, lseek returns the offset of
the pointer's new position, measured in
bytes from the file beginning.
* On error, lseek returns -1L, and sets
errno to one of the following:
EBADF Bad file number
EINVAL Invalid argument
On devices incapable of seeking (such as
terminals and printers), the return value is
undefined.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
See Also:
filelength
fseek
ftell
getc
open
sopen
ungetc
_write
write
Example:
#include <sys\stat.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
int main(void)
{
int handle;
char msg[] = "This is a test";
char ch;
/* create a file */
handle = open("TEST.$$$", O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
/* write some data to the file */
write(handle, msg, strlen(msg));
/* seek to the begining of the file */
lseek(handle, 0L, SEEK_SET);
/* reads chars from the file until we hit EOF */
do
{
read(handle, &ch, 1);
printf("%c", ch);
} while (!eof(handle));
close(handle);
return 0;
}
=============
open, sopen <IO.H>
=============
Open a file for reading or writing
Declaration:
* open:
#include <fcntl.h>
#include <sys\stat.h>
int open(const char *path, int access [ , unsigned mode ] );
* sopen:
#include <fcntl.h>
#include <sys\stat.h>
#include <share.h>
#include <IO.H>
sopen(path, access, shflag, mode)
Remarks:
open and sopen open the file specified by
path, then prepare it for reading and/or
writing. (sopen prepares path for shared
reading and/or writing).
Argument| What Argument Is/Does
--------+----------------------------------------------------------------
path | File that the function opens and prepares for reading/writing
access | Specifies the file-access mode that "path" opens in
| File-access symbolic constants are defined in FCNTL.H
mode | Specifies the mode that the newly created "path" opens in
| (used only if "access" includes O_CREATE).
--------+----------------------------------------------------------------
shflag | Specifies the type of file-sharing allowed on "path"
| File-sharing symbolic constants are defined in SHARE.H
sopen is a macro defined as:
open(path, (access) | (shflag), mode)
sopen is included for compatibility with
earlier versions of Turbo C, Borland C++,
and other compilers.
On successfully opening the file, both
routines set the file pointer (which marks
the current position in the file) to the
beginning of the file.
The maximum number of simultaneously open
files is defined by HANDLE_MAX.
See "Creating a file in a given mode" for
more information.
Return Value:
* On success, both return the file handle (a non-negative
integer) and set the file pointer to the beginning of the file.
* On error, both return -1 and set errno to one of the following:
ENOENT (No such file or directory)
EMFILE (Too many open files)
EACCES (Permission denied)
EINVACC (Invalid access code)
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
* NOTE: On UNIX version 7, the O_type flags
are not defined. UNIX System III uses all
of the O_type flags except O_BINARY and
O_TEXT.
See Also:
chmod
chsize
close
creat/_creat
creatnew
creattemp
dup/dup2
fdopen
filelength
fopen
freopen
getftime
lock
lseek
_open
read
unlock
write/_write
Examples:
open example
sopen example
sopen example
===============
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>
#include <process.h>
#include <share.h>
#include <stdio.h>
int main(void)
{
int handle;
int status;
handle = sopen("c:\\autoexec.bat", O_RDONLY, SH_DENYNO, S_IREAD);
if (!handle)
{
printf("sopen failed\n");
exit(1);
}
status = access("c:\\autoexec.bat", 6);
if (status == 0)
printf("read/write access allowed\n");
else
printf("read/write access not allowed\n");
close(handle);
return 0;
}
open 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;
}
mode argument (open and sopen) and
modeMask argument (umask)
====================================
Symbolic Constant| Access Permission
------------------+--------------------------
S_IWRITE | Permission to write
S_IREAD | Permission to read
S_IREAD|S_IWRITE | Permission to read/write
These symbolic constants for modeMask and
mode are defined in SYS\STAT.H.
access argument to open and sopen
===================================
You construct the access argument by bitwise
OR'ing flags from the O_xxxx Read/Write and
Other Access flag lists.
You must use one (and only one) Read/Write
flag; you can OR the remaining Other Access
flags in any logical combination.
If you don't specify O_BINARY or O_TEXT in
access, the file is opened in the translation
mode set by _fmode.
shflag argument to sopen
==========================
Under DOS 3.0 or later, only one of the
SH_DENYxx values can be included in a single
call to sopen.
These file-sharing attributes are in addition
to any locking performed on the files.
Creating a file in a given mode
=================================
To create a file in a particular mode, you
can either
* assign to _fmode, or
* call open or sopen with O_CREAT and
O_TRUNC OR'ed with O_BINARY or O_TEXT
For example, this call
open("xmp", O_CREAT | O_TRUNC | O_BINARY, S_IREAD)
creates a binary-mode, read-only file named
XMP and, if XMP already exists, truncates its
length to 0 bytes.
=========
setmode <IO.H>
=========
Sets mode of an open file
Declaration: int setmode(int handle, int amode);
Remarks:
setmode sets the mode of the open file
associated with handle to either binary or
text.
The argument amode must have a value of
either O_BINARY or O_TEXT, never both. (These
symbolic constants are defined in FCNTL.H.)
Return Value
* On success, setmode returns the previous translation mode.
* On error, it returns -1 and sets errno to EINVAL (invalid argument).
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | | |
+-----+------+---------+--------+----------+
See Also:
_creat
_open
creat
open
Example:
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
int main(void)
{
int result;
result = setmode(fileno(stdprn), O_TEXT);
if (result == -1)
perror("Mode not available\n");
else
printf("Mode successfully switched\n");
return 0;
}
======
tell <IO.H>
======
Gets current position of file pointer
Declaration: long tell(int handle);
Remarks:
tell gets the current position of the file
pointer associated with handle and expresses
it as the number of bytes from the beginning
of the file.
Return Value:
* On success, tell returns the current file
pointer position.
* On error, returns -1 (long) and sets
errno to EBADF (bad file number).
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | Yes | Yes | | |
+-----+------+---------+--------+----------+
See Also:
fgetpos
fseek
ftell
lseek
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 | O_APPEND)) == -1)
{
perror("Error:");
return 1;
}
write(handle, msg, strlen(msg));
printf("The file pointer is at byte %ld\n", tell(handle));
close(handle);
return 0;
}
=======
umask <IO.H>
=======
Sets file read/write permission mask
Declaration: unsigned umask (unsigned modeMask);
Remarks:
umask sets the access permission mask used by
open and creat. Bits that are set in modeMask
will be cleared in the access permission of
files subsequently created by open and creat.
modeMask can be one of the S_I... symbolic
constants defined in <SYS\STAT.H>:
Return Value
The previous value of the mask. There is no
error return.
Portability:
+ DOS + UNIX + Windows + ANSI C + C++ Only +
| Yes | | Yes | | |
+-----+------+---------+--------+----------+
Example:
#include <io.h>
#include <stdio.h>
#include <sys\stat.h>
#define FILENAME "TEST.$$$"
int main(void)
{
unsigned oldmask;
FILE *f;
struct stat statbuf;
/* Cause subsequent files to be created as read-only */
oldmask = umask(S_IWRITE);
printf("Old mask = 0x%x\n",oldmask);
/* Create a zero-length file */
if ((f = fopen(FILENAME,"w+")) == NULL)
{
perror("Unable to create output file");
return (1);
}
fclose(f);
/* Verify that the file is read-only */
if (stat(FILENAME,&statbuf) != 0)
{
perror("Unable to get information about output file");
return (1);
}
if (statbuf.st_mode & S_IWRITE)
printf("Error! %s is writable!\n",FILENAME);
else
printf("Success! %s is not writable.\n",FILENAME);
return (0);
}