Example (_setmode -- Set File Translation Mode)
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)
****************************************************************************/
}