Syntax
#include <fcntl.h> #include <io.h> int _setmode(int handle, int mode);Description
Value
Use _setmode to change the translation mode of a file handle. The translation mode only affects the read and write functions. _setmode does not affect the translation mode of streams.
If a file handle is acquired other than by a call to open, creat, _sopen or fileno, you should call _setmode for that file handle before using it within the read or write functions.
Value
This example uses open to create the file setmode.dat and writes to it. The program then uses _setmode to change the translation mode of setmode.dat from binary to text.
#include <stdio.h>#include <stdlib.h> #include <fcntl.h> #include <io.h> #include <sys\stat.h> #define FILENAME "setmode.dat" /* routine to validate return codes */ void ckrc(int rc) { if (-1 == rc) { printf("Unexpected return code = -1\n"); remove(FILENAME); exit(EXIT_FAILURE); } } int main(void) { int h; int xfer; int mode; char rbuf[256]; char wbuf[] = "123\n456\n"; ckrc(h = open(FILENAME, O_CREAT|O_RDWR|O_TRUNC|O_TEXT, S_IREAD|S_IWRITE)); ckrc(write(h, wbuf, sizeof(wbuf))); /* write the file (text) */ ckrc(lseek(h, 0, SEEK_SET)); /* seek back to the start of the file */ ckrc(xfer = read(h, rbuf, 5)); /* read the file text */ printf("Read in %d characters (4 expected)\n", xfer); ckrc(mode = _setmode(h, O_BINARY)); if (O_TEXT == mode) printf("Mode changed from binary to text\n"); else printf("Previous mode was not text (unexpected)\n"); ckrc(xfer = read(h, rbuf, 5)); /* read the file (binary) */ printf("Read in %d characters (5 expected)\n", xfer); ckrc(close(h)); remove(FILENAME); return 0; /**************************************************************************** The output should be: Read in 4 characters (4 expected) Mode changed from binary to text Read in 5 characters (5 expected) ****************************************************************************/ }Related Information