file.c 81.9 KB
Newer Older
1 2 3 4 5 6 7
/*
 * msvcrt.dll file functions
 *
 * Copyright 1996,1998 Marcus Meissner
 * Copyright 1996 Jukka Iivonen
 * Copyright 1997,2000 Uwe Bonnes
 * Copyright 2000 Jon Griffiths
8
 * Copyright 2004 Eric Pouech
9
 * Copyright 2004 Juan Lang
10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
23
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 25 26
 *
 * TODO
 * Use the file flag hints O_SEQUENTIAL, O_RANDOM, O_SHORT_LIVED
27
 */
28 29 30 31

#include "config.h"
#include "wine/port.h"

32
#include <time.h>
33
#include <stdarg.h>
34
#include <stdio.h>
35 36 37
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
38
#include <sys/types.h>
39

40 41 42
#include "windef.h"
#include "winbase.h"
#include "winreg.h"
43
#include "winternl.h"
44 45
#include "msvcrt.h"

46
#include "wine/unicode.h"
47

48 49 50
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
51 52

/* for stat mode, permissions apply to all,owner and group */
53 54 55
#define ALL_S_IREAD  (MSVCRT__S_IREAD  | (MSVCRT__S_IREAD  >> 3) | (MSVCRT__S_IREAD  >> 6))
#define ALL_S_IWRITE (MSVCRT__S_IWRITE | (MSVCRT__S_IWRITE >> 3) | (MSVCRT__S_IWRITE >> 6))
#define ALL_S_IEXEC  (MSVCRT__S_IEXEC  | (MSVCRT__S_IEXEC  >> 3) | (MSVCRT__S_IEXEC  >> 6))
56 57

/* _access() bit flags FIXME: incomplete */
58
#define MSVCRT_W_OK      0x02
59

60
/* values for wxflag in file descriptor */
61 62 63 64 65
#define WX_OPEN           0x01
#define WX_ATEOF          0x02
#define WX_DONTINHERIT    0x10
#define WX_APPEND         0x20
#define WX_TEXT           0x80
66

67
/* FIXME: this should be allocated dynamically */
68
#define MSVCRT_MAX_FILES 2048
69

70
typedef struct {
71
    HANDLE              handle;
72
    unsigned char       wxflag;
73 74 75 76
    DWORD               unkn[7]; /* critical section and init flag */       
} ioinfo;

static ioinfo MSVCRT_fdesc[MSVCRT_MAX_FILES];
77

78 79 80 81 82
MSVCRT_FILE MSVCRT__iob[3];

static int MSVCRT_fdstart = 3; /* first unallocated fd */
static int MSVCRT_fdend = 3; /* highest allocated fd */

83
static MSVCRT_FILE* MSVCRT_fstreams[2048];
84 85
static int   MSVCRT_stream_idx;

86 87 88 89 90 91 92 93 94 95 96
/* INTERNAL: process umask */
static int MSVCRT_umask = 0;

/* INTERNAL: Static buffer for temp file name */
static char MSVCRT_tmpname[MAX_PATH];

static const unsigned int EXE = 'e' << 16 | 'x' << 8 | 'e';
static const unsigned int BAT = 'b' << 16 | 'a' << 8 | 't';
static const unsigned int CMD = 'c' << 16 | 'm' << 8 | 'd';
static const unsigned int COM = 'c' << 16 | 'o' << 8 | 'm';

97
#define TOUL(x) (ULONGLONG)(x)
98 99 100 101 102
static const ULONGLONG WCEXE = TOUL('e') << 32 | TOUL('x') << 16 | TOUL('e');
static const ULONGLONG WCBAT = TOUL('b') << 32 | TOUL('a') << 16 | TOUL('t');
static const ULONGLONG WCCMD = TOUL('c') << 32 | TOUL('m') << 16 | TOUL('d');
static const ULONGLONG WCCOM = TOUL('c') << 32 | TOUL('o') << 16 | TOUL('m');

103 104 105 106 107 108 109 110 111 112
/* This critical section protects the tables MSVCRT_fdesc and MSVCRT_fstreams,
 * and their related indexes, MSVCRT_fdstart, MSVCRT_fdend,
 * and MSVCRT_stream_idx, from race conditions.
 * It doesn't protect against race conditions manipulating the underlying files
 * or flags; doing so would probably be better accomplished with per-file
 * protection, rather than locking the whole table for every change.
 */
static CRITICAL_SECTION MSVCRT_file_cs;
#define LOCK_FILES()    do { EnterCriticalSection(&MSVCRT_file_cs); } while (0)
#define UNLOCK_FILES()  do { LeaveCriticalSection(&MSVCRT_file_cs); } while (0)
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
static void msvcrt_stat64_to_stat(const struct MSVCRT__stat64 *buf64, struct MSVCRT__stat *buf)
{
    buf->st_dev   = buf64->st_dev;
    buf->st_ino   = buf64->st_ino;
    buf->st_mode  = buf64->st_mode;
    buf->st_nlink = buf64->st_nlink;
    buf->st_uid   = buf64->st_uid;
    buf->st_gid   = buf64->st_gid;
    buf->st_rdev  = buf64->st_rdev;
    buf->st_size  = buf64->st_size;
    buf->st_atime = buf64->st_atime;
    buf->st_mtime = buf64->st_mtime;
    buf->st_ctime = buf64->st_ctime;
}

static void msvcrt_stat64_to_stati64(const struct MSVCRT__stat64 *buf64, struct MSVCRT__stati64 *buf)
{
    buf->st_dev   = buf64->st_dev;
    buf->st_ino   = buf64->st_ino;
    buf->st_mode  = buf64->st_mode;
    buf->st_nlink = buf64->st_nlink;
    buf->st_uid   = buf64->st_uid;
    buf->st_gid   = buf64->st_gid;
    buf->st_rdev  = buf64->st_rdev;
    buf->st_size  = buf64->st_size;
    buf->st_atime = buf64->st_atime;
    buf->st_mtime = buf64->st_mtime;
    buf->st_ctime = buf64->st_ctime;
142
}
143

144 145
static inline BOOL msvcrt_is_valid_fd(int fd)
{
146
  return fd >= 0 && fd < MSVCRT_fdend && (MSVCRT_fdesc[fd].wxflag & WX_OPEN);
147 148
}

149 150 151 152 153 154
/* INTERNAL: Get the HANDLE for a fd
 * This doesn't lock the table, because a failure will result in
 * INVALID_HANDLE_VALUE being returned, which should be handled correctly.  If
 * it returns a valid handle which is about to be closed, a subsequent call
 * will fail, most likely in a sane way.
 */
155
static HANDLE msvcrt_fdtoh(int fd)
156
{
157
  if (!msvcrt_is_valid_fd(fd))
158 159
  {
    WARN(":fd (%d) - no handle!\n",fd);
160
    *MSVCRT___doserrno() = 0;
161
    *MSVCRT__errno() = MSVCRT_EBADF;
162
    return INVALID_HANDLE_VALUE;
163
  }
164 165
  if (MSVCRT_fdesc[fd].handle == INVALID_HANDLE_VALUE) FIXME("wtf\n");
  return MSVCRT_fdesc[fd].handle;
166 167 168
}

/* INTERNAL: free a file entry fd */
169
static void msvcrt_free_fd(int fd)
170
{
171
  LOCK_FILES();
172
  MSVCRT_fdesc[fd].handle = INVALID_HANDLE_VALUE;
173
  MSVCRT_fdesc[fd].wxflag = 0;
174
  TRACE(":fd (%d) freed\n",fd);
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  if (fd < 3) /* don't use 0,1,2 for user files */
  {
    switch (fd)
    {
    case 0: SetStdHandle(STD_INPUT_HANDLE,  NULL); break;
    case 1: SetStdHandle(STD_OUTPUT_HANDLE, NULL); break;
    case 2: SetStdHandle(STD_ERROR_HANDLE,  NULL); break;
    }
  }
  else
  {
    if (fd == MSVCRT_fdend - 1)
      MSVCRT_fdend--;
    if (fd < MSVCRT_fdstart)
      MSVCRT_fdstart = fd;
  }
191
  UNLOCK_FILES();
192 193
}

194
/* INTERNAL: Allocate an fd slot from a Win32 HANDLE, starting from fd */
195
/* caller must hold the files lock */
196
static int msvcrt_alloc_fd_from(HANDLE hand, int flag, int fd)
197 198 199 200 201 202
{
  if (fd >= MSVCRT_MAX_FILES)
  {
    WARN(":files exhausted!\n");
    return -1;
  }
203
  MSVCRT_fdesc[fd].handle = hand;
204
  MSVCRT_fdesc[fd].wxflag = WX_OPEN | (flag & (WX_DONTINHERIT | WX_APPEND | WX_TEXT));
205 206

  /* locate next free slot */
207 208
  if (fd == MSVCRT_fdstart && fd == MSVCRT_fdend)
    MSVCRT_fdstart = MSVCRT_fdend + 1;
209
  else
210
    while (MSVCRT_fdstart < MSVCRT_fdend &&
211
     MSVCRT_fdesc[MSVCRT_fdstart].handle != INVALID_HANDLE_VALUE)
212
      MSVCRT_fdstart++;
213 214 215 216
  /* update last fd in use */
  if (fd >= MSVCRT_fdend)
    MSVCRT_fdend = fd + 1;
  TRACE("fdstart is %d, fdend is %d\n", MSVCRT_fdstart, MSVCRT_fdend);
217

218 219 220 221 222 223 224
  switch (fd)
  {
  case 0: SetStdHandle(STD_INPUT_HANDLE,  hand); break;
  case 1: SetStdHandle(STD_OUTPUT_HANDLE, hand); break;
  case 2: SetStdHandle(STD_ERROR_HANDLE,  hand); break;
  }

225 226 227
  return fd;
}

228 229 230
/* INTERNAL: Allocate an fd slot from a Win32 HANDLE */
static int msvcrt_alloc_fd(HANDLE hand, int flag)
{
231 232 233
  int ret;

  LOCK_FILES();
234
  TRACE(":handle (%p) allocating fd (%d)\n",hand,MSVCRT_fdstart);
235 236 237
  ret = msvcrt_alloc_fd_from(hand, flag, MSVCRT_fdstart);
  UNLOCK_FILES();
  return ret;
238 239
}

240 241
/* INTERNAL: Allocate a FILE* for an fd slot */
/* caller must hold the files lock */
242 243
static MSVCRT_FILE* msvcrt_alloc_fp(void)
{
244
  unsigned int i;
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

  for (i = 3; i < sizeof(MSVCRT_fstreams) / sizeof(MSVCRT_fstreams[0]); i++)
  {
    if (!MSVCRT_fstreams[i] || MSVCRT_fstreams[i]->_flag == 0)
    {
      if (!MSVCRT_fstreams[i])
      {
        if (!(MSVCRT_fstreams[i] = MSVCRT_calloc(sizeof(MSVCRT_FILE),1)))
          return NULL;
        if (i == MSVCRT_stream_idx) MSVCRT_stream_idx++;
      }
      return MSVCRT_fstreams[i];
    }
  }
  return NULL;
}

/* INTERNAL: initialize a FILE* from an open fd */
static int msvcrt_init_fp(MSVCRT_FILE* file, int fd, unsigned stream_flags)
264 265
{
  TRACE(":fd (%d) allocating FILE*\n",fd);
266
  if (!msvcrt_is_valid_fd(fd))
267 268
  {
    WARN(":invalid fd %d\n",fd);
269
    *MSVCRT___doserrno() = 0;
270
    *MSVCRT__errno() = MSVCRT_EBADF;
271
    return -1;
272
  }
273 274 275 276 277 278
  memset(file, 0, sizeof(*file));
  file->_file = fd;
  file->_flag = stream_flags;

  TRACE(":got FILE* (%p)\n",file);
  return 0;
279 280
}

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
/* INTERNAL: Create an inheritance data block (for spawned process)
 * The inheritance block is made of:
 *      00      int     nb of file descriptor (NBFD)
 *      04      char    file flags (wxflag): repeated for each fd
 *      4+NBFD  HANDLE  file handle: repeated for each fd
 */
unsigned msvcrt_create_io_inherit_block(STARTUPINFOA* si)
{
  int         fd;
  char*       wxflag_ptr;
  HANDLE*     handle_ptr;

  si->cbReserved2 = sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * MSVCRT_fdend;
  si->lpReserved2 = MSVCRT_calloc(si->cbReserved2, 1);
  if (!si->lpReserved2)
  {
    si->cbReserved2 = 0;
    return FALSE;
  }
  wxflag_ptr = (char*)si->lpReserved2 + sizeof(unsigned);
  handle_ptr = (HANDLE*)(wxflag_ptr + MSVCRT_fdend * sizeof(char));

  *(unsigned*)si->lpReserved2 = MSVCRT_fdend;
  for (fd = 0; fd < MSVCRT_fdend; fd++)
  {
    /* to be inherited, we need it to be open, and that DONTINHERIT isn't set */
    if ((MSVCRT_fdesc[fd].wxflag & (WX_OPEN | WX_DONTINHERIT)) == WX_OPEN)
    {
      *wxflag_ptr = MSVCRT_fdesc[fd].wxflag;
      *handle_ptr = MSVCRT_fdesc[fd].handle;
    }
    else
    {
      *wxflag_ptr = 0;
      *handle_ptr = INVALID_HANDLE_VALUE;
    }
    wxflag_ptr++; handle_ptr++;
  } 
  return TRUE;
}
321

322 323 324
/* INTERNAL: Set up all file descriptors, 
 * as well as default streams (stdin, stderr and stdout) 
 */
325
void msvcrt_init_io(void)
326
{
327 328
  STARTUPINFOA  si;
  int           i;
329

330
  InitializeCriticalSection(&MSVCRT_file_cs);
331
  MSVCRT_file_cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": MSVCRT_file_cs");
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
  GetStartupInfoA(&si);
  if (si.cbReserved2 != 0 && si.lpReserved2 != NULL)
  {
    char*       wxflag_ptr;
    HANDLE*     handle_ptr;

    MSVCRT_fdend = *(unsigned*)si.lpReserved2;

    wxflag_ptr = (char*)(si.lpReserved2 + sizeof(unsigned));
    handle_ptr = (HANDLE*)(wxflag_ptr + MSVCRT_fdend * sizeof(char));

    MSVCRT_fdend = min(MSVCRT_fdend, sizeof(MSVCRT_fdesc) / sizeof(MSVCRT_fdesc[0]));
    for (i = 0; i < MSVCRT_fdend; i++)
    {
      if ((*wxflag_ptr & WX_OPEN) && *handle_ptr != INVALID_HANDLE_VALUE)
      {
        MSVCRT_fdesc[i].wxflag  = *wxflag_ptr;
        MSVCRT_fdesc[i].handle = *handle_ptr;
      }
      else
      {
        MSVCRT_fdesc[i].wxflag  = 0;
        MSVCRT_fdesc[i].handle = INVALID_HANDLE_VALUE;
      }
      wxflag_ptr++; handle_ptr++;
    }
    for (MSVCRT_fdstart = 3; MSVCRT_fdstart < MSVCRT_fdend; MSVCRT_fdstart++)
        if (MSVCRT_fdesc[MSVCRT_fdstart].handle == INVALID_HANDLE_VALUE) break;
  }

  if (!(MSVCRT_fdesc[0].wxflag & WX_OPEN) || MSVCRT_fdesc[0].handle == INVALID_HANDLE_VALUE)
  {
    DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_INPUT_HANDLE),
Eric Pouech's avatar
Eric Pouech committed
365
                    GetCurrentProcess(), &MSVCRT_fdesc[0].handle, 0, TRUE, 
366 367 368 369 370 371
                    DUPLICATE_SAME_ACCESS);
    MSVCRT_fdesc[0].wxflag = WX_OPEN | WX_TEXT;
  }
  if (!(MSVCRT_fdesc[1].wxflag & WX_OPEN) || MSVCRT_fdesc[1].handle == INVALID_HANDLE_VALUE)
  {
    DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_OUTPUT_HANDLE),
Eric Pouech's avatar
Eric Pouech committed
372
                    GetCurrentProcess(), &MSVCRT_fdesc[1].handle, 0, TRUE, 
373 374 375 376 377 378
                    DUPLICATE_SAME_ACCESS);
    MSVCRT_fdesc[1].wxflag = WX_OPEN | WX_TEXT;
  }
  if (!(MSVCRT_fdesc[2].wxflag & WX_OPEN) || MSVCRT_fdesc[2].handle == INVALID_HANDLE_VALUE)
  {
    DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_ERROR_HANDLE),
Eric Pouech's avatar
Eric Pouech committed
379
                    GetCurrentProcess(), &MSVCRT_fdesc[2].handle, 0, TRUE, 
380 381 382
                    DUPLICATE_SAME_ACCESS);
    MSVCRT_fdesc[2].wxflag = WX_OPEN | WX_TEXT;
  }
383

384 385
  TRACE(":handles (%p)(%p)(%p)\n",MSVCRT_fdesc[0].handle,
	MSVCRT_fdesc[1].handle,MSVCRT_fdesc[2].handle);
386

387
  memset(MSVCRT__iob,0,3*sizeof(MSVCRT_FILE));
388 389 390
  for (i = 0; i < 3; i++)
  {
    /* FILE structs for stdin/out/err are static and never deleted */
391
    MSVCRT_fstreams[i] = &MSVCRT__iob[i];
392
    MSVCRT__iob[i]._file = i;
393 394
    MSVCRT__iob[i]._tmpfname = NULL;
    MSVCRT__iob[i]._flag = (i == 0) ? MSVCRT__IOREAD : MSVCRT__IOWRT;
395
  }
396
  MSVCRT_stream_idx = 3;
397 398
}

399 400 401 402 403 404
/* INTERNAL: Flush stdio file buffer */
static int msvcrt_flush_buffer(MSVCRT_FILE* file)
{
  if(file->_bufsiz) {
        int cnt=file->_ptr-file->_base;
        if(cnt>0 && _write(file->_file, file->_base, cnt) != cnt) {
405 406
            file->_flag |= MSVCRT__IOERR;
            return MSVCRT_EOF;
407 408 409 410 411 412 413 414 415 416 417 418 419 420
        }
        file->_ptr=file->_base;
        file->_cnt=file->_bufsiz;
  }
  return 0;
}

/* INTERNAL: Allocate stdio file buffer */
static void msvcrt_alloc_buffer(MSVCRT_FILE* file)
{
	file->_base = MSVCRT_calloc(MSVCRT_BUFSIZ,1);
	if(file->_base) {
		file->_bufsiz = MSVCRT_BUFSIZ;
		file->_flag |= MSVCRT__IOMYBUF;
421
	} else {
Mike McCormack's avatar
Mike McCormack committed
422
		file->_base = (char*)(&file->_charbuf);
423 424 425 426 427 428 429
		/* put here 2 ??? */
		file->_bufsiz = sizeof(file->_charbuf);
	}
	file->_ptr = file->_base;
	file->_cnt = 0;
}

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
/* INTERNAL: Convert integer to base32 string (0-9a-v), 0 becomes "" */
static void msvcrt_int_to_base32(int num, char *str)
{
  char *p;
  int n = num;
  int digits = 0;

  while (n != 0)
  {
    n >>= 5;
    digits++;
  }
  p = str + digits;
  *p = 0;
  while (--p >= str)
  {
    *p = (num & 31) + '0';
    if (*p > '9')
      *p += ('a' - '0' - 10);
    num >>= 5;
  }
}

453 454 455
/*********************************************************************
 *		__p__iob(MSVCRT.@)
 */
456
MSVCRT_FILE * CDECL __p__iob(void)
457 458 459 460 461 462 463
{
 return &MSVCRT__iob[0];
}

/*********************************************************************
 *		_access (MSVCRT.@)
 */
464
int CDECL _access(const char *filename, int mode)
465 466 467
{
  DWORD attr = GetFileAttributesA(filename);

468
  TRACE("(%s,%d) %d\n",filename,mode,attr);
469

470
  if (!filename || attr == INVALID_FILE_ATTRIBUTES)
471
  {
472
    msvcrt_set_errno(GetLastError());
473 474
    return -1;
  }
475
  if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
476
  {
477
    msvcrt_set_errno(ERROR_ACCESS_DENIED);
478 479 480 481 482
    return -1;
  }
  return 0;
}

483 484 485
/*********************************************************************
 *		_waccess (MSVCRT.@)
 */
486
int CDECL _waccess(const MSVCRT_wchar_t *filename, int mode)
487 488 489
{
  DWORD attr = GetFileAttributesW(filename);

490
  TRACE("(%s,%d) %d\n",debugstr_w(filename),mode,attr);
491

492
  if (!filename || attr == INVALID_FILE_ATTRIBUTES)
493
  {
494
    msvcrt_set_errno(GetLastError());
495 496
    return -1;
  }
497
  if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
498
  {
499
    msvcrt_set_errno(ERROR_ACCESS_DENIED);
500 501 502 503
    return -1;
  }
  return 0;
}
504 505 506 507

/*********************************************************************
 *		_chmod (MSVCRT.@)
 */
508
int CDECL _chmod(const char *path, int flags)
509 510 511
{
  DWORD oldFlags = GetFileAttributesA(path);

512
  if (oldFlags != INVALID_FILE_ATTRIBUTES)
513
  {
514
    DWORD newFlags = (flags & MSVCRT__S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
515 516 517 518 519
      oldFlags | FILE_ATTRIBUTE_READONLY;

    if (newFlags == oldFlags || SetFileAttributesA(path, newFlags))
      return 0;
  }
520
  msvcrt_set_errno(GetLastError());
521 522 523
  return -1;
}

524 525 526
/*********************************************************************
 *		_wchmod (MSVCRT.@)
 */
527
int CDECL _wchmod(const MSVCRT_wchar_t *path, int flags)
528 529 530
{
  DWORD oldFlags = GetFileAttributesW(path);

531
  if (oldFlags != INVALID_FILE_ATTRIBUTES)
532
  {
533
    DWORD newFlags = (flags & MSVCRT__S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
534 535 536 537 538
      oldFlags | FILE_ATTRIBUTE_READONLY;

    if (newFlags == oldFlags || SetFileAttributesW(path, newFlags))
      return 0;
  }
539
  msvcrt_set_errno(GetLastError());
540 541 542
  return -1;
}

543 544 545
/*********************************************************************
 *		_unlink (MSVCRT.@)
 */
546
int CDECL _unlink(const char *path)
547
{
548
  TRACE("%s\n",debugstr_a(path));
549 550
  if(DeleteFileA(path))
    return 0;
551
  TRACE("failed (%d)\n",GetLastError());
552
  msvcrt_set_errno(GetLastError());
553 554 555 556 557 558
  return -1;
}

/*********************************************************************
 *		_wunlink (MSVCRT.@)
 */
559
int CDECL _wunlink(const MSVCRT_wchar_t *path)
560 561 562 563
{
  TRACE("(%s)\n",debugstr_w(path));
  if(DeleteFileW(path))
    return 0;
564
  TRACE("failed (%d)\n",GetLastError());
565
  msvcrt_set_errno(GetLastError());
566 567 568
  return -1;
}

569
/* _flushall calls MSVCRT_fflush which calls _flushall */
570
int CDECL MSVCRT_fflush(MSVCRT_FILE* file);
571 572 573 574

/*********************************************************************
 *		_flushall (MSVCRT.@)
 */
575
int CDECL _flushall(void)
576 577 578
{
  int i, num_flushed = 0;

579
  LOCK_FILES();
580 581
  for (i = 3; i < MSVCRT_stream_idx; i++)
    if (MSVCRT_fstreams[i] && MSVCRT_fstreams[i]->_flag)
582 583 584 585
    {
#if 0
      /* FIXME: flush, do not commit */
      if (_commit(i) == -1)
586 587
	if (MSVCRT_fstreams[i])
	  MSVCRT_fstreams[i]->_flag |= MSVCRT__IOERR;
588
#endif
589 590
      if(MSVCRT_fstreams[i]->_flag & MSVCRT__IOWRT) {
	MSVCRT_fflush(MSVCRT_fstreams[i]);
591 592 593
        num_flushed++;
      }
    }
594
  UNLOCK_FILES();
595 596 597 598 599 600 601 602

  TRACE(":flushed (%d) handles\n",num_flushed);
  return num_flushed;
}

/*********************************************************************
 *		fflush (MSVCRT.@)
 */
603
int CDECL MSVCRT_fflush(MSVCRT_FILE* file)
604 605 606
{
  if(!file) {
	_flushall();
607
  } else if(file->_flag & MSVCRT__IOWRT) {
608 609 610
  	int res=msvcrt_flush_buffer(file);
  	return res;
  }
611
  return 0;
612 613
}

614 615 616
/*********************************************************************
 *		_close (MSVCRT.@)
 */
617
int CDECL _close(int fd)
618
{
619 620
  HANDLE hand;
  int ret;
621

622 623
  LOCK_FILES();
  hand = msvcrt_fdtoh(fd);
624
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
625
  if (hand == INVALID_HANDLE_VALUE)
626 627
    ret = -1;
  else if (!CloseHandle(hand))
628
  {
629
    WARN(":failed-last error (%d)\n",GetLastError());
630
    msvcrt_set_errno(GetLastError());
631
    ret = -1;
632
  }
633 634 635 636 637 638
  else
  {
    msvcrt_free_fd(fd);
    ret = 0;
  }
  UNLOCK_FILES();
639
  TRACE(":ok\n");
640
  return ret;
641 642 643 644 645
}

/*********************************************************************
 *		_commit (MSVCRT.@)
 */
646
int CDECL _commit(int fd)
647
{
648
  HANDLE hand = msvcrt_fdtoh(fd);
649

650
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
651 652 653 654 655 656 657 658 659 660 661 662
  if (hand == INVALID_HANDLE_VALUE)
    return -1;

  if (!FlushFileBuffers(hand))
  {
    if (GetLastError() == ERROR_INVALID_HANDLE)
    {
      /* FlushFileBuffers fails for console handles
       * so we ignore this error.
       */
      return 0;
    }
663
    TRACE(":failed-last error (%d)\n",GetLastError());
664
    msvcrt_set_errno(GetLastError());
665 666 667 668 669 670
    return -1;
  }
  TRACE(":ok\n");
  return 0;
}

671 672 673 674 675 676 677 678
/*********************************************************************
 *		_dup2 (MSVCRT.@)
 * NOTES
 * MSDN isn't clear on this point, but the remarks for _pipe,
 * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt__pipe.asp
 * indicate file descriptors duplicated with _dup and _dup2 are always
 * inheritable.
 */
679
int CDECL _dup2(int od, int nd)
680 681 682 683
{
  int ret;

  TRACE("(od=%d, nd=%d)\n", od, nd);
684
  LOCK_FILES();
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
  if (nd < MSVCRT_MAX_FILES && msvcrt_is_valid_fd(od))
  {
    HANDLE handle;

    if (DuplicateHandle(GetCurrentProcess(), MSVCRT_fdesc[od].handle,
     GetCurrentProcess(), &handle, 0, TRUE, DUPLICATE_SAME_ACCESS))
    {
      int wxflag = MSVCRT_fdesc[od].wxflag & ~MSVCRT__O_NOINHERIT;

      if (msvcrt_is_valid_fd(nd))
        _close(nd);
      ret = msvcrt_alloc_fd_from(handle, wxflag, nd);
      if (ret == -1)
      {
        CloseHandle(handle);
        *MSVCRT__errno() = MSVCRT_EMFILE;
      }
      else
      {
        /* _dup2 returns 0, not nd, on success */
        ret = 0;
      }
    }
    else
    {
      ret = -1;
      msvcrt_set_errno(GetLastError());
    }
  }
  else
  {
    *MSVCRT__errno() = MSVCRT_EBADF;
    ret = -1;
  }
719
  UNLOCK_FILES();
720 721 722 723 724 725
  return ret;
}

/*********************************************************************
 *		_dup (MSVCRT.@)
 */
726
int CDECL _dup(int od)
727
{
728 729 730 731
  int fd, ret;
 
  LOCK_FILES();
  fd = MSVCRT_fdstart;
732
  if (_dup2(od, fd) == 0)
733 734 735 736 737
    ret = fd;
  else
    ret = -1;
  UNLOCK_FILES();
  return ret;
738 739
}

740 741 742
/*********************************************************************
 *		_eof (MSVCRT.@)
 */
743
int CDECL _eof(int fd)
744
{
Mike McCormack's avatar
Mike McCormack committed
745 746
  DWORD curpos,endpos;
  LONG hcurpos,hendpos;
747
  HANDLE hand = msvcrt_fdtoh(fd);
748

749
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
750 751 752 753

  if (hand == INVALID_HANDLE_VALUE)
    return -1;

754
  if (MSVCRT_fdesc[fd].wxflag & WX_ATEOF) return TRUE;
755 756

  /* Otherwise we do it the hard way */
757
  hcurpos = hendpos = 0;
Mike McCormack's avatar
Mike McCormack committed
758
  curpos = SetFilePointer(hand, 0, &hcurpos, FILE_CURRENT);
759
  endpos = SetFilePointer(hand, 0, &hendpos, FILE_END);
760

761
  if (curpos == endpos && hcurpos == hendpos)
762 763
  {
    /* FIXME: shouldn't WX_ATEOF be set here? */
764
    return TRUE;
765
  }
766

767
  SetFilePointer(hand, curpos, &hcurpos, FILE_BEGIN);
768 769 770 771 772 773
  return FALSE;
}

/*********************************************************************
 *		_fcloseall (MSVCRT.@)
 */
774
int CDECL MSVCRT__fcloseall(void)
775 776 777
{
  int num_closed = 0, i;

778
  LOCK_FILES();
779 780
  for (i = 3; i < MSVCRT_stream_idx; i++)
    if (MSVCRT_fstreams[i] && MSVCRT_fstreams[i]->_flag &&
781
        !MSVCRT_fclose(MSVCRT_fstreams[i]))
782
      num_closed++;
783
  UNLOCK_FILES();
784 785 786 787 788

  TRACE(":closed (%d) handles\n",num_closed);
  return num_closed;
}

789 790 791 792
/* free everything on process exit */
void msvcrt_free_io(void)
{
    MSVCRT__fcloseall();
793 794 795 796 797 798 799
    /* The Win32 _fcloseall() function explicitly doesn't close stdin,
     * stdout, and stderr (unlike GNU), so we need to fclose() them here
     * or they won't get flushed.
     */
    MSVCRT_fclose(&MSVCRT__iob[0]);
    MSVCRT_fclose(&MSVCRT__iob[1]);
    MSVCRT_fclose(&MSVCRT__iob[2]);
800
    MSVCRT_file_cs.DebugInfo->Spare[0] = 0;
801
    DeleteCriticalSection(&MSVCRT_file_cs);
802 803
}

804
/*********************************************************************
805
 *		_lseeki64 (MSVCRT.@)
806
 */
807
__int64 CDECL _lseeki64(int fd, __int64 offset, int whence)
808
{
809
  HANDLE hand = msvcrt_fdtoh(fd);
Mike McCormack's avatar
Mike McCormack committed
810
  LARGE_INTEGER ofs, ret;
811

812
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
813 814 815 816 817
  if (hand == INVALID_HANDLE_VALUE)
    return -1;

  if (whence < 0 || whence > 2)
  {
818
    *MSVCRT__errno() = MSVCRT_EINVAL;
819 820 821
    return -1;
  }

Mike McCormack's avatar
Mike McCormack committed
822
  TRACE(":fd (%d) to %s pos %s\n",
823
        fd,wine_dbgstr_longlong(offset),
824
        (whence==SEEK_SET)?"SEEK_SET":
825 826 827
        (whence==SEEK_CUR)?"SEEK_CUR":
        (whence==SEEK_END)?"SEEK_END":"UNKNOWN");

Mike McCormack's avatar
Mike McCormack committed
828 829
  ofs.QuadPart = offset;
  if (SetFilePointerEx(hand, ofs, &ret, whence))
830
  {
831
    MSVCRT_fdesc[fd].wxflag &= ~WX_ATEOF;
832
    /* FIXME: What if we seek _to_ EOF - is EOF set? */
833

Mike McCormack's avatar
Mike McCormack committed
834
    return ret.QuadPart;
835
  }
836
  TRACE(":error-last error (%d)\n",GetLastError());
837
  msvcrt_set_errno(GetLastError());
838 839 840
  return -1;
}

841 842 843
/*********************************************************************
 *		_lseek (MSVCRT.@)
 */
844
LONG CDECL _lseek(int fd, LONG offset, int whence)
845 846 847 848
{
    return _lseeki64(fd, offset, whence);
}

849 850 851 852 853
/*********************************************************************
 *		_locking (MSVCRT.@)
 *
 * This is untested; the underlying LockFile doesn't work yet.
 */
854
int CDECL _locking(int fd, int mode, LONG nbytes)
855 856 857 858 859
{
  BOOL ret;
  DWORD cur_locn;
  HANDLE hand = msvcrt_fdtoh(fd);

860
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
861 862 863 864 865
  if (hand == INVALID_HANDLE_VALUE)
    return -1;

  if (mode < 0 || mode > 4)
  {
866
    *MSVCRT__errno() = MSVCRT_EINVAL;
867 868 869
    return -1;
  }

870
  TRACE(":fd (%d) by 0x%08x mode %s\n",
871 872 873 874 875
        fd,nbytes,(mode==MSVCRT__LK_UNLCK)?"_LK_UNLCK":
        (mode==MSVCRT__LK_LOCK)?"_LK_LOCK":
        (mode==MSVCRT__LK_NBLCK)?"_LK_NBLCK":
        (mode==MSVCRT__LK_RLCK)?"_LK_RLCK":
        (mode==MSVCRT__LK_NBRLCK)?"_LK_NBRLCK":
876 877
                          "UNKNOWN");

878
  if ((cur_locn = SetFilePointer(hand, 0L, NULL, SEEK_CUR)) == INVALID_SET_FILE_POINTER)
879 880
  {
    FIXME ("Seek failed\n");
881
    *MSVCRT__errno() = MSVCRT_EINVAL; /* FIXME */
882 883
    return -1;
  }
884
  if (mode == MSVCRT__LK_LOCK || mode == MSVCRT__LK_RLCK)
885 886 887 888 889 890 891
  {
    int nretry = 10;
    ret = 1; /* just to satisfy gcc */
    while (nretry--)
    {
      ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
      if (ret) break;
892
      Sleep(1);
893 894
    }
  }
895
  else if (mode == MSVCRT__LK_UNLCK)
896 897 898 899 900 901 902
    ret = UnlockFile(hand, cur_locn, 0L, nbytes, 0L);
  else
    ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
  /* FIXME - what about error settings? */
  return ret ? 0 : -1;
}

903 904 905
/*********************************************************************
 *		fseek (MSVCRT.@)
 */
906
int CDECL MSVCRT_fseek(MSVCRT_FILE* file, long offset, int whence)
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
{
  /* Flush output if needed */
  if(file->_flag & MSVCRT__IOWRT)
	msvcrt_flush_buffer(file);

  if(whence == SEEK_CUR && file->_flag & MSVCRT__IOREAD ) {
	offset -= file->_cnt;
  }
  /* Discard buffered input */
  file->_cnt = 0;
  file->_ptr = file->_base;
  /* Reset direction of i/o */
  if(file->_flag & MSVCRT__IORW) {
        file->_flag &= ~(MSVCRT__IOREAD|MSVCRT__IOWRT);
  }
  return (_lseek(file->_file,offset,whence) == -1)?-1:0;
}

925 926 927
/*********************************************************************
 *		_chsize (MSVCRT.@)
 */
928
int CDECL _chsize(int fd, long size)
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
{
    LONG cur, pos;
    HANDLE handle;
    BOOL ret = FALSE;

    TRACE("(fd=%d, size=%ld)\n", fd, size);

    LOCK_FILES();

    handle = msvcrt_fdtoh(fd);
    if (handle != INVALID_HANDLE_VALUE)
    {
        /* save the current file pointer */
        cur = _lseek(fd, 0, SEEK_CUR);
        if (cur >= 0)
        {
            pos = _lseek(fd, size, SEEK_SET);
            if (pos >= 0)
            {
                ret = SetEndOfFile(handle);
                if (!ret) msvcrt_set_errno(GetLastError());
            }

            /* restore the file pointer */
            _lseek(fd, cur, SEEK_SET);
        }
    }

    UNLOCK_FILES();
    return ret ? 0 : -1;
}

961 962 963
/*********************************************************************
 *		clearerr (MSVCRT.@)
 */
964
void CDECL MSVCRT_clearerr(MSVCRT_FILE* file)
965 966 967 968 969
{
  TRACE(":file (%p) fd (%d)\n",file,file->_file);
  file->_flag &= ~(MSVCRT__IOERR | MSVCRT__IOEOF);
}

970 971 972
/*********************************************************************
 *		rewind (MSVCRT.@)
 */
973
void CDECL MSVCRT_rewind(MSVCRT_FILE* file)
974 975
{
  TRACE(":file (%p) fd (%d)\n",file,file->_file);
976 977
  MSVCRT_fseek(file, 0L, SEEK_SET);
  MSVCRT_clearerr(file);
978 979
}

980 981 982 983 984 985 986
static int msvcrt_get_flags(const char* mode, int *open_flags, int* stream_flags)
{
  int plus = strchr(mode, '+') != NULL;

  switch(*mode++)
  {
  case 'R': case 'r':
987
    *open_flags = plus ? MSVCRT__O_RDWR : MSVCRT__O_RDONLY;
988 989 990
    *stream_flags = plus ? MSVCRT__IORW : MSVCRT__IOREAD;
    break;
  case 'W': case 'w':
991
    *open_flags = MSVCRT__O_CREAT | MSVCRT__O_TRUNC | (plus  ? MSVCRT__O_RDWR : MSVCRT__O_WRONLY);
992 993 994
    *stream_flags = plus ? MSVCRT__IORW : MSVCRT__IOWRT;
    break;
  case 'A': case 'a':
995
    *open_flags = MSVCRT__O_CREAT | MSVCRT__O_APPEND | (plus  ? MSVCRT__O_RDWR : MSVCRT__O_WRONLY);
996 997 998 999 1000 1001 1002 1003 1004 1005
    *stream_flags = plus ? MSVCRT__IORW : MSVCRT__IOWRT;
    break;
  default:
    return -1;
  }

  while (*mode)
    switch (*mode++)
    {
    case 'B': case 'b':
1006 1007
      *open_flags |=  MSVCRT__O_BINARY;
      *open_flags &= ~MSVCRT__O_TEXT;
1008 1009
      break;
    case 'T': case 't':
1010 1011
      *open_flags |=  MSVCRT__O_TEXT;
      *open_flags &= ~MSVCRT__O_BINARY;
1012 1013 1014 1015 1016 1017 1018 1019 1020
      break;
    case '+':
      break;
    default:
      FIXME(":unknown flag %c not supported\n",mode[-1]);
    }
  return 0;
}

1021 1022 1023
/*********************************************************************
 *		_fdopen (MSVCRT.@)
 */
1024
MSVCRT_FILE* CDECL MSVCRT__fdopen(int fd, const char *mode)
1025
{
1026 1027
  int open_flags, stream_flags;
  MSVCRT_FILE* file;
1028

1029 1030
  if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1) return NULL;

1031 1032 1033 1034
  LOCK_FILES();
  if (!(file = msvcrt_alloc_fp()))
    file = NULL;
  else if (msvcrt_init_fp(file, fd, stream_flags) == -1)
1035 1036 1037 1038 1039
  {
    file->_flag = 0;
    file = NULL;
  }
  else TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,mode,file);
1040
  UNLOCK_FILES();
1041 1042 1043 1044

  return file;
}

1045 1046 1047
/*********************************************************************
 *		_wfdopen (MSVCRT.@)
 */
1048
MSVCRT_FILE* CDECL MSVCRT__wfdopen(int fd, const MSVCRT_wchar_t *mode)
1049
{
1050 1051 1052 1053
  unsigned mlen = strlenW(mode);
  char *modea = MSVCRT_calloc(mlen + 1, 1);
  MSVCRT_FILE* file = NULL;
  int open_flags, stream_flags;
1054

1055 1056 1057 1058
  if (modea &&
      WideCharToMultiByte(CP_ACP,0,mode,mlen,modea,mlen,NULL,NULL))
  {
      if (msvcrt_get_flags(modea, &open_flags, &stream_flags) == -1) return NULL;
1059 1060 1061 1062
      LOCK_FILES();
      if (!(file = msvcrt_alloc_fp()))
        file = NULL;
      else if (msvcrt_init_fp(file, fd, stream_flags) == -1)
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
      {
        file->_flag = 0;
        file = NULL;
      }
      else
      {
        if (file)
          MSVCRT_rewind(file); /* FIXME: is this needed ??? */
        TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,debugstr_w(mode),file);
      }
1073
      UNLOCK_FILES();
1074
  }
1075 1076 1077
  return file;
}

1078 1079 1080
/*********************************************************************
 *		_filelength (MSVCRT.@)
 */
1081
LONG CDECL _filelength(int fd)
1082
{
1083
  LONG curPos = _lseek(fd, 0, SEEK_CUR);
1084 1085
  if (curPos != -1)
  {
1086
    LONG endPos = _lseek(fd, 0, SEEK_END);
1087 1088 1089
    if (endPos != -1)
    {
      if (endPos != curPos)
1090
        _lseek(fd, curPos, SEEK_SET);
1091 1092 1093 1094 1095 1096
      return endPos;
    }
  }
  return -1;
}

1097 1098 1099
/*********************************************************************
 *		_filelengthi64 (MSVCRT.@)
 */
1100
__int64 CDECL _filelengthi64(int fd)
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
{
  __int64 curPos = _lseeki64(fd, 0, SEEK_CUR);
  if (curPos != -1)
  {
    __int64 endPos = _lseeki64(fd, 0, SEEK_END);
    if (endPos != -1)
    {
      if (endPos != curPos)
        _lseeki64(fd, curPos, SEEK_SET);
      return endPos;
    }
  }
  return -1;
}

1116 1117 1118
/*********************************************************************
 *		_fileno (MSVCRT.@)
 */
1119
int CDECL MSVCRT__fileno(MSVCRT_FILE* file)
1120 1121 1122 1123 1124 1125
{
  TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
  return file->_file;
}

/*********************************************************************
1126
 *		_fstat64 (MSVCRT.@)
1127
 */
1128
int CDECL MSVCRT__fstat64(int fd, struct MSVCRT__stat64* buf)
1129 1130
{
  DWORD dw;
1131
  DWORD type;
1132
  BY_HANDLE_FILE_INFORMATION hfi;
1133
  HANDLE hand = msvcrt_fdtoh(fd);
1134 1135 1136 1137 1138 1139 1140 1141

  TRACE(":fd (%d) stat (%p)\n",fd,buf);
  if (hand == INVALID_HANDLE_VALUE)
    return -1;

  if (!buf)
  {
    WARN(":failed-NULL buf\n");
1142
    msvcrt_set_errno(ERROR_INVALID_PARAMETER);
1143 1144 1145 1146
    return -1;
  }

  memset(&hfi, 0, sizeof(hfi));
1147
  memset(buf, 0, sizeof(struct MSVCRT__stat64));
1148 1149
  type = GetFileType(hand);
  if (type == FILE_TYPE_PIPE)
1150
  {
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
    buf->st_dev = buf->st_rdev = fd;
    buf->st_mode = S_IFIFO;
    buf->st_nlink = 1;
  }
  else if (type == FILE_TYPE_CHAR)
  {
    buf->st_dev = buf->st_rdev = fd;
    buf->st_mode = S_IFCHR;
    buf->st_nlink = 1;
  }
  else /* FILE_TYPE_DISK etc. */
  {
    if (!GetFileInformationByHandle(hand, &hfi))
    {
      WARN(":failed-last error (%d)\n",GetLastError());
      msvcrt_set_errno(ERROR_INVALID_PARAMETER);
      return -1;
    }
    buf->st_mode = S_IFREG | S_IREAD;
    if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
      buf->st_mode |= S_IWRITE;
    buf->st_size  = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
    RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
    buf->st_atime = dw;
    RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
    buf->st_mtime = buf->st_ctime = dw;
    buf->st_nlink = hfi.nNumberOfLinks;
1178
  }
1179
  TRACE(":dwFileAttributes = 0x%x, mode set to 0x%x\n",hfi.dwFileAttributes,
1180
   buf->st_mode);
1181 1182 1183
  return 0;
}

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
/*********************************************************************
 *		_fstati64 (MSVCRT.@)
 */
int CDECL MSVCRT__fstati64(int fd, struct MSVCRT__stati64* buf)
{
  int ret;
  struct MSVCRT__stat64 buf64;

  ret = MSVCRT__fstat64(fd, &buf64);
  if (!ret)
    msvcrt_stat64_to_stati64(&buf64, buf);
  return ret;
}

1198 1199 1200
/*********************************************************************
 *		_fstat (MSVCRT.@)
 */
1201
int CDECL MSVCRT__fstat(int fd, struct MSVCRT__stat* buf)
1202
{ int ret;
1203
  struct MSVCRT__stat64 buf64;
1204

1205
  ret = MSVCRT__fstat64(fd, &buf64);
1206
  if (!ret)
1207
      msvcrt_stat64_to_stat(&buf64, buf);
1208 1209 1210
  return ret;
}

1211 1212 1213
/*********************************************************************
 *		_futime (MSVCRT.@)
 */
1214
int CDECL _futime(int fd, struct MSVCRT__utimbuf *t)
1215
{
1216
  HANDLE hand = msvcrt_fdtoh(fd);
1217 1218 1219 1220
  FILETIME at, wt;

  if (!t)
  {
1221
    MSVCRT_time_t currTime;
1222
    MSVCRT_time(&currTime);
1223
    RtlSecondsSince1970ToTime(currTime, (LARGE_INTEGER *)&at);
1224 1225 1226 1227
    memcpy(&wt, &at, sizeof(wt));
  }
  else
  {
1228
    RtlSecondsSince1970ToTime(t->actime, (LARGE_INTEGER *)&at);
1229 1230 1231
    if (t->actime == t->modtime)
      memcpy(&wt, &at, sizeof(wt));
    else
1232
      RtlSecondsSince1970ToTime(t->modtime, (LARGE_INTEGER *)&wt);
1233 1234 1235 1236
  }

  if (!SetFileTime(hand, NULL, &at, &wt))
  {
1237
    msvcrt_set_errno(GetLastError());
1238 1239 1240 1241 1242 1243 1244 1245
    return -1 ;
  }
  return 0;
}

/*********************************************************************
 *		_get_osfhandle (MSVCRT.@)
 */
1246
long CDECL _get_osfhandle(int fd)
1247
{
1248
  HANDLE hand = msvcrt_fdtoh(fd);
1249
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
1250

1251
  return (long)hand;
1252 1253 1254 1255 1256
}

/*********************************************************************
 *		_isatty (MSVCRT.@)
 */
1257
int CDECL _isatty(int fd)
1258
{
1259
  HANDLE hand = msvcrt_fdtoh(fd);
1260

1261
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
1262 1263 1264
  if (hand == INVALID_HANDLE_VALUE)
    return 0;

1265
  return GetFileType(hand) == FILE_TYPE_CHAR? 1 : 0;
1266 1267 1268 1269 1270
}

/*********************************************************************
 *		_mktemp (MSVCRT.@)
 */
1271
char * CDECL _mktemp(char *pattern)
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
{
  int numX = 0;
  char *retVal = pattern;
  int id;
  char letter = 'a';

  while(*pattern)
    numX = (*pattern++ == 'X')? numX + 1 : 0;
  if (numX < 5)
    return NULL;
  pattern--;
  id = GetCurrentProcessId();
  numX = 6;
  while(numX--)
  {
    int tempNum = id / 10;
    *pattern-- = id - (tempNum * 10) + '0';
    id = tempNum;
  }
  pattern++;
  do
  {
1294
    *pattern = letter++;
1295
    if (GetFileAttributesA(retVal) == INVALID_FILE_ATTRIBUTES &&
1296
        GetLastError() == ERROR_FILE_NOT_FOUND)
1297
      return retVal;
1298
  } while(letter <= 'z');
1299 1300 1301
  return NULL;
}

1302 1303 1304
/*********************************************************************
 *		_wmktemp (MSVCRT.@)
 */
1305
MSVCRT_wchar_t * CDECL _wmktemp(MSVCRT_wchar_t *pattern)
1306 1307
{
  int numX = 0;
1308
  MSVCRT_wchar_t *retVal = pattern;
1309
  int id;
1310
  MSVCRT_wchar_t letter = 'a';
1311 1312

  while(*pattern)
1313
    numX = (*pattern++ == 'X')? numX + 1 : 0;
1314 1315 1316 1317 1318 1319 1320 1321
  if (numX < 5)
    return NULL;
  pattern--;
  id = GetCurrentProcessId();
  numX = 6;
  while(numX--)
  {
    int tempNum = id / 10;
1322
    *pattern-- = id - (tempNum * 10) + '0';
1323 1324 1325 1326 1327
    id = tempNum;
  }
  pattern++;
  do
  {
1328
    if (GetFileAttributesW(retVal) == INVALID_FILE_ATTRIBUTES &&
1329 1330 1331
        GetLastError() == ERROR_FILE_NOT_FOUND)
      return retVal;
    *pattern = letter++;
1332
  } while(letter != '|');
1333 1334 1335
  return NULL;
}

1336 1337 1338
static unsigned split_oflags(unsigned oflags)
{
    int         wxflags = 0;
1339
    unsigned unsupp; /* until we support everything */
1340 1341

    if (oflags & MSVCRT__O_APPEND)              wxflags |= WX_APPEND;
1342
    if (oflags & MSVCRT__O_BINARY)              {/* Nothing to do */}
1343
    else if (oflags & MSVCRT__O_TEXT)           wxflags |= WX_TEXT;
1344
    else if (*__p__fmode() & MSVCRT__O_BINARY)  {/* Nothing to do */}
1345 1346 1347
    else                                        wxflags |= WX_TEXT; /* default to TEXT*/
    if (oflags & MSVCRT__O_NOINHERIT)           wxflags |= WX_DONTINHERIT;

1348 1349 1350 1351 1352 1353 1354 1355
    if ((unsupp = oflags & ~(
                    MSVCRT__O_BINARY|MSVCRT__O_TEXT|MSVCRT__O_APPEND|
                    MSVCRT__O_TRUNC|MSVCRT__O_EXCL|MSVCRT__O_CREAT|
                    MSVCRT__O_RDWR|MSVCRT__O_WRONLY|MSVCRT__O_TEMPORARY|
                    MSVCRT__O_NOINHERIT|
                    MSVCRT__O_SEQUENTIAL|MSVCRT__O_RANDOM|MSVCRT__O_SHORT_LIVED
                    )))
        ERR(":unsupported oflags 0x%04x\n",unsupp);
1356 1357 1358 1359

    return wxflags;
}

1360 1361 1362
/*********************************************************************
 *              _pipe (MSVCRT.@)
 */
1363
int CDECL _pipe(int *pfds, unsigned int psize, int textmode)
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
{
  int ret = -1;
  SECURITY_ATTRIBUTES sa;
  HANDLE readHandle, writeHandle;

  if (!pfds)
  {
    *MSVCRT__errno() = MSVCRT_EINVAL;
    return -1;
  }

  sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  sa.bInheritHandle = !(textmode & MSVCRT__O_NOINHERIT);
  sa.lpSecurityDescriptor = NULL;
  if (CreatePipe(&readHandle, &writeHandle, &sa, psize))
  {
    unsigned int wxflags = split_oflags(textmode);
    int fd;

1383
    LOCK_FILES();
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
    fd = msvcrt_alloc_fd(readHandle, wxflags);
    if (fd != -1)
    {
      pfds[0] = fd;
      fd = msvcrt_alloc_fd(writeHandle, wxflags);
      if (fd != -1)
      {
        pfds[1] = fd;
        ret = 0;
      }
      else
      {
        _close(pfds[0]);
        CloseHandle(writeHandle);
        *MSVCRT__errno() = MSVCRT_EMFILE;
      }
    }
    else
    {
      CloseHandle(readHandle);
      CloseHandle(writeHandle);
      *MSVCRT__errno() = MSVCRT_EMFILE;
    }
1407
    UNLOCK_FILES();
1408 1409 1410 1411 1412 1413 1414
  }
  else
    msvcrt_set_errno(GetLastError());

  return ret;
}

1415
/*********************************************************************
1416
 *              _sopen (MSVCRT.@)
1417
 */
1418
int CDECL MSVCRT__sopen( const char *path, int oflags, int shflags, ... )
1419
{
1420 1421
  va_list ap;
  int pmode;
1422
  DWORD access = 0, creation = 0, attrib;
1423
  DWORD sharing;
1424
  int wxflag = 0, fd;
1425
  HANDLE hand;
1426
  SECURITY_ATTRIBUTES sa;
1427

1428 1429 1430 1431

  TRACE(":file (%s) oflags: 0x%04x shflags: 0x%04x\n",
        path, oflags, shflags);

1432 1433
  wxflag = split_oflags(oflags);
  switch (oflags & (MSVCRT__O_RDONLY | MSVCRT__O_WRONLY | MSVCRT__O_RDWR))
1434
  {
1435 1436 1437
  case MSVCRT__O_RDONLY: access |= GENERIC_READ; break;
  case MSVCRT__O_WRONLY: access |= GENERIC_WRITE; break;
  case MSVCRT__O_RDWR:   access |= GENERIC_WRITE | GENERIC_READ; break;
1438 1439
  }

1440
  if (oflags & MSVCRT__O_CREAT)
1441
  {
1442 1443 1444 1445
    va_start(ap, shflags);
      pmode = va_arg(ap, int);
    va_end(ap);

1446
    if(pmode & ~(MSVCRT__S_IREAD | MSVCRT__S_IWRITE))
1447 1448 1449
      FIXME(": pmode 0x%04x ignored\n", pmode);
    else
      WARN(": pmode 0x%04x ignored\n", pmode);
1450

1451
    if (oflags & MSVCRT__O_EXCL)
1452
      creation = CREATE_NEW;
1453
    else if (oflags & MSVCRT__O_TRUNC)
1454 1455 1456 1457
      creation = CREATE_ALWAYS;
    else
      creation = OPEN_ALWAYS;
  }
1458
  else  /* no MSVCRT__O_CREAT */
1459
  {
1460
    if (oflags & MSVCRT__O_TRUNC)
1461 1462 1463 1464
      creation = TRUNCATE_EXISTING;
    else
      creation = OPEN_EXISTING;
  }
1465
  
1466 1467
  switch( shflags )
  {
1468
    case MSVCRT__SH_DENYRW:
1469 1470
      sharing = 0L;
      break;
1471
    case MSVCRT__SH_DENYWR:
1472 1473
      sharing = FILE_SHARE_READ;
      break;
1474
    case MSVCRT__SH_DENYRD:
1475 1476
      sharing = FILE_SHARE_WRITE;
      break;
1477
    case MSVCRT__SH_DENYNO:
1478 1479 1480 1481 1482 1483
      sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
      break;
    default:
      ERR( "Unhandled shflags 0x%x\n", shflags );
      return -1;
  }
1484 1485
  attrib = FILE_ATTRIBUTE_NORMAL;

1486
  if (oflags & MSVCRT__O_TEMPORARY)
1487 1488 1489 1490 1491
  {
      attrib |= FILE_FLAG_DELETE_ON_CLOSE;
      access |= DELETE;
      sharing |= FILE_SHARE_DELETE;
  }
1492

1493 1494
  sa.nLength              = sizeof( SECURITY_ATTRIBUTES );
  sa.lpSecurityDescriptor = NULL;
1495
  sa.bInheritHandle       = (oflags & MSVCRT__O_NOINHERIT) ? FALSE : TRUE;
1496

1497
  hand = CreateFileA(path, access, sharing, &sa, creation, attrib, 0);
1498

1499
  if (hand == INVALID_HANDLE_VALUE)  {
1500
    WARN(":failed-last error (%d)\n",GetLastError());
1501
    msvcrt_set_errno(GetLastError());
1502 1503 1504
    return -1;
  }

1505
  fd = msvcrt_alloc_fd(hand, wxflag);
1506

1507
  TRACE(":fd (%d) handle (%p)\n",fd, hand);
1508 1509 1510
  return fd;
}

1511
/*********************************************************************
1512
 *              _wsopen (MSVCRT.@)
1513
 */
1514
int CDECL MSVCRT__wsopen( const MSVCRT_wchar_t* path, int oflags, int shflags, ... )
1515
{
1516
  const unsigned int len = strlenW(path);
1517
  char *patha = MSVCRT_calloc(len + 1,1);
1518 1519 1520 1521 1522 1523 1524
  va_list ap;
  int pmode;

  va_start(ap, shflags);
  pmode = va_arg(ap, int);
  va_end(ap);

1525 1526
  if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
  {
1527
    int retval = MSVCRT__sopen(patha,oflags,shflags,pmode);
1528 1529 1530 1531
    MSVCRT_free(patha);
    return retval;
  }

1532
  msvcrt_set_errno(GetLastError());
1533 1534 1535
  return -1;
}

Eric Kohl's avatar
Eric Kohl committed
1536
/*********************************************************************
1537 1538
 *              _open (MSVCRT.@)
 */
1539
int CDECL _open( const char *path, int flags, ... )
1540 1541 1542
{
  va_list ap;

1543
  if (flags & MSVCRT__O_CREAT)
1544 1545 1546 1547 1548
  {
    int pmode;
    va_start(ap, flags);
    pmode = va_arg(ap, int);
    va_end(ap);
1549
    return MSVCRT__sopen( path, flags, MSVCRT__SH_DENYNO, pmode );
1550 1551
  }
  else
1552
    return MSVCRT__sopen( path, flags, MSVCRT__SH_DENYNO);
1553 1554 1555 1556
}

/*********************************************************************
 *              _wopen (MSVCRT.@)
Eric Kohl's avatar
Eric Kohl committed
1557
 */
1558
int CDECL _wopen(const MSVCRT_wchar_t *path,int flags,...)
Eric Kohl's avatar
Eric Kohl committed
1559
{
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
  const unsigned int len = strlenW(path);
  char *patha = MSVCRT_calloc(len + 1,1);
  va_list ap;
  int pmode;

  va_start(ap, flags);
  pmode = va_arg(ap, int);
  va_end(ap);

  if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
  {
    int retval = _open(patha,flags,pmode);
    MSVCRT_free(patha);
    return retval;
  }

1576
  msvcrt_set_errno(GetLastError());
1577
  return -1;
Eric Kohl's avatar
Eric Kohl committed
1578 1579
}

1580 1581 1582
/*********************************************************************
 *		_creat (MSVCRT.@)
 */
1583
int CDECL _creat(const char *path, int flags)
1584
{
1585
  int usedFlags = (flags & MSVCRT__O_TEXT)| MSVCRT__O_CREAT| MSVCRT__O_WRONLY| MSVCRT__O_TRUNC;
1586
  return _open(path, usedFlags);
1587 1588
}

1589 1590 1591
/*********************************************************************
 *		_wcreat (MSVCRT.@)
 */
1592
int CDECL _wcreat(const MSVCRT_wchar_t *path, int flags)
1593
{
1594
  int usedFlags = (flags & MSVCRT__O_TEXT)| MSVCRT__O_CREAT| MSVCRT__O_WRONLY| MSVCRT__O_TRUNC;
1595
  return _wopen(path, usedFlags);
1596 1597
}

1598 1599 1600
/*********************************************************************
 *		_open_osfhandle (MSVCRT.@)
 */
1601
int CDECL _open_osfhandle(long handle, int oflags)
1602
{
1603 1604
  int fd;

1605
  /* MSVCRT__O_RDONLY (0) always matches, so set the read flag
1606
   * MFC's CStdioFile clears O_RDONLY (0)! if it wants to write to the
1607 1608
   * file, so set the write flag. It also only sets MSVCRT__O_TEXT if it wants
   * text - it never sets MSVCRT__O_BINARY.
1609
   */
1610 1611
  /* don't let split_oflags() decide the mode if no mode is passed */
  if (!(oflags & (MSVCRT__O_BINARY | MSVCRT__O_TEXT)))
1612
      oflags |= MSVCRT__O_BINARY;
1613

1614 1615
  fd = msvcrt_alloc_fd((HANDLE)handle, split_oflags(oflags));
  TRACE(":handle (%ld) fd (%d) flags 0x%08x\n", handle, fd, oflags);
1616 1617 1618 1619 1620 1621
  return fd;
}

/*********************************************************************
 *		_rmtmp (MSVCRT.@)
 */
1622
int CDECL _rmtmp(void)
1623 1624 1625
{
  int num_removed = 0, i;

1626
  LOCK_FILES();
1627 1628
  for (i = 3; i < MSVCRT_stream_idx; i++)
    if (MSVCRT_fstreams[i] && MSVCRT_fstreams[i]->_tmpfname)
1629
    {
1630
      MSVCRT_fclose(MSVCRT_fstreams[i]);
1631 1632
      num_removed++;
    }
1633
  UNLOCK_FILES();
1634 1635 1636 1637 1638 1639

  if (num_removed)
    TRACE(":removed (%d) temp files\n",num_removed);
  return num_removed;
}

1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
/*********************************************************************
 * (internal) remove_cr
 *
 *    Remove all \r inplace.
 * return the number of \r removed
 */
static unsigned int remove_cr(char *buf, unsigned int count)
{
    unsigned int i, j;

    for (i = 0; i < count; i++) if (buf[i] == '\r') break;
    for (j = i + 1; j < count; j++) if (buf[j] != '\r') buf[i++] = buf[j];
    return count - i;
}

1655
/*********************************************************************
1656
 * (internal) read_i
1657
 */
1658
static int read_i(int fd, void *buf, unsigned int count)
1659
{
1660
  DWORD num_read;
1661
  char *bufstart = buf;
1662
  HANDLE hand = msvcrt_fdtoh(fd);
1663

1664
  /* Don't trace small reads, it gets *very* annoying */
1665
  if (count > 4)
1666
    TRACE(":fd (%d) handle (%p) buf (%p) len (%d)\n",fd,hand,buf,count);
1667 1668 1669
  if (hand == INVALID_HANDLE_VALUE)
    return -1;

1670
  /* Reading single bytes in O_TEXT mode makes things slow
1671
   * So read big chunks
1672
   */
1673 1674
    if (ReadFile(hand, bufstart, count, &num_read, NULL))
    {
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
        if (MSVCRT_fdesc[fd].wxflag & WX_TEXT)
        {
            int i;
            /* in text mode, a ctrl-z signals EOF */
            for (i=0; i<num_read; i++)
            {
                if (bufstart[i] == 0x1a)
                {
                    num_read = i;
                    break;
                }
            }
        }
1688 1689 1690 1691 1692 1693 1694 1695
        if (num_read != count)
        {
            MSVCRT_fdesc[fd].wxflag |= WX_ATEOF;
            TRACE(":EOF %s\n",debugstr_an(buf,num_read));
        }
    }
    else
    {
1696
        TRACE(":failed-last error (%d)\n",GetLastError());
1697 1698
        return -1;
    }
1699 1700

  if (count > 4)
1701
      TRACE("(%u), %s\n",num_read,debugstr_an(buf, num_read));
1702
  return num_read;
1703 1704
}

1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
/*********************************************************************
 *		_read (MSVCRT.@)
 */
int CDECL _read(int fd, void *buf, unsigned int count)
{
  int num_read;
  num_read = read_i(fd, buf, count);
  if (num_read>0 && MSVCRT_fdesc[fd].wxflag & WX_TEXT)
  {
      num_read -= remove_cr(buf,num_read);
  }
  return num_read;
}

1719 1720 1721
/*********************************************************************
 *		_setmode (MSVCRT.@)
 */
1722
int CDECL _setmode(int fd,int mode)
1723
{
1724
  int ret = MSVCRT_fdesc[fd].wxflag & WX_TEXT ? MSVCRT__O_TEXT : MSVCRT__O_BINARY;
1725
  if (mode & (~(MSVCRT__O_TEXT|MSVCRT__O_BINARY)))
1726
    FIXME("fd (%d) mode (0x%08x) unknown\n",fd,mode);
1727
  if ((mode & MSVCRT__O_TEXT) == MSVCRT__O_TEXT)
1728
    MSVCRT_fdesc[fd].wxflag |= WX_TEXT;
1729
  else
1730
    MSVCRT_fdesc[fd].wxflag &= ~WX_TEXT;
1731
  return ret;
1732 1733 1734
}

/*********************************************************************
1735
 *		_stat64 (MSVCRT.@)
1736
 */
1737
int CDECL MSVCRT__stat64(const char* path, struct MSVCRT__stat64 * buf)
1738 1739 1740
{
  DWORD dw;
  WIN32_FILE_ATTRIBUTE_DATA hfi;
1741
  unsigned short mode = ALL_S_IREAD;
1742 1743 1744 1745 1746 1747
  int plen;

  TRACE(":file (%s) buf(%p)\n",path,buf);

  if (!GetFileAttributesExA(path, GetFileExInfoStandard, &hfi))
  {
1748
      TRACE("failed (%d)\n",GetLastError());
1749
      msvcrt_set_errno(ERROR_FILE_NOT_FOUND);
1750 1751 1752
      return -1;
  }

1753
  memset(buf,0,sizeof(struct MSVCRT__stat64));
1754

1755
  /* FIXME: rdev isn't drive num, despite what the docs say-what is it?
1756
     Bon 011120: This FIXME seems incorrect
1757 1758
                 Also a letter as first char isn't enough to be classified
		 as a drive letter
1759 1760 1761
  */
  if (isalpha(*path)&& (*(path+1)==':'))
    buf->st_dev = buf->st_rdev = toupper(*path) - 'A'; /* drive num */
1762
  else
1763
    buf->st_dev = buf->st_rdev = _getdrive() - 1;
1764 1765 1766 1767 1768 1769

  plen = strlen(path);

  /* Dir, or regular file? */
  if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
      (path[plen-1] == '\\'))
1770
    mode |= (MSVCRT__S_IFDIR | ALL_S_IEXEC);
1771 1772
  else
  {
1773
    mode |= MSVCRT__S_IFREG;
1774 1775 1776
    /* executable? */
    if (plen > 6 && path[plen-4] == '.')  /* shortest exe: "\x.exe" */
    {
1777 1778
      unsigned int ext = tolower(path[plen-1]) | (tolower(path[plen-2]) << 8) |
                                 (tolower(path[plen-3]) << 16);
1779
      if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
1780
          mode |= ALL_S_IEXEC;
1781 1782 1783 1784
    }
  }

  if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1785
    mode |= ALL_S_IWRITE;
1786 1787 1788

  buf->st_mode  = mode;
  buf->st_nlink = 1;
1789
  buf->st_size  = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
1790
  RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1791
  buf->st_atime = dw;
1792
  RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1793
  buf->st_mtime = buf->st_ctime = dw;
1794 1795
  TRACE("%d %d 0x%08lx%08lx %ld %ld %ld\n", buf->st_mode,buf->st_nlink,
        (long)(buf->st_size >> 32),(long)buf->st_size,
1796
        (long)buf->st_atime,(long)buf->st_mtime,(long)buf->st_ctime);
1797 1798 1799
  return 0;
}

1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
/*********************************************************************
 *		_stati64 (MSVCRT.@)
 */
int CDECL MSVCRT__stati64(const char* path, struct MSVCRT__stati64 * buf)
{
  int ret;
  struct MSVCRT__stat64 buf64;

  ret = MSVCRT__stat64(path, &buf64);
  if (!ret)
    msvcrt_stat64_to_stati64(&buf64, buf);
  return ret;
}

1814 1815 1816
/*********************************************************************
 *		_stat (MSVCRT.@)
 */
1817
int CDECL MSVCRT__stat(const char* path, struct MSVCRT__stat * buf)
1818
{ int ret;
1819
  struct MSVCRT__stat64 buf64;
1820

1821
  ret = MSVCRT__stat64( path, &buf64);
1822
  if (!ret)
1823
      msvcrt_stat64_to_stat(&buf64, buf);
1824 1825 1826
  return ret;
}

1827
/*********************************************************************
1828
 *		_wstat64 (MSVCRT.@)
1829
 */
1830
int CDECL MSVCRT__wstat64(const MSVCRT_wchar_t* path, struct MSVCRT__stat64 * buf)
1831 1832 1833
{
  DWORD dw;
  WIN32_FILE_ATTRIBUTE_DATA hfi;
1834
  unsigned short mode = ALL_S_IREAD;
1835 1836 1837 1838 1839 1840
  int plen;

  TRACE(":file (%s) buf(%p)\n",debugstr_w(path),buf);

  if (!GetFileAttributesExW(path, GetFileExInfoStandard, &hfi))
  {
1841
      TRACE("failed (%d)\n",GetLastError());
1842
      msvcrt_set_errno(ERROR_FILE_NOT_FOUND);
1843 1844 1845
      return -1;
  }

1846
  memset(buf,0,sizeof(struct MSVCRT__stat64));
1847

1848 1849
  /* FIXME: rdev isn't drive num, despite what the docs says-what is it? */
  if (MSVCRT_iswalpha(*path))
1850
    buf->st_dev = buf->st_rdev = toupperW(*path - 'A'); /* drive num */
1851
  else
1852
    buf->st_dev = buf->st_rdev = _getdrive() - 1;
1853

1854
  plen = strlenW(path);
1855 1856 1857

  /* Dir, or regular file? */
  if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1858
      (path[plen-1] == '\\'))
1859
    mode |= (MSVCRT__S_IFDIR | ALL_S_IEXEC);
1860 1861
  else
  {
1862
    mode |= MSVCRT__S_IFREG;
1863
    /* executable? */
1864
    if (plen > 6 && path[plen-4] == '.')  /* shortest exe: "\x.exe" */
1865
    {
1866 1867
      ULONGLONG ext = tolowerW(path[plen-1]) | (tolowerW(path[plen-2]) << 16) |
                               ((ULONGLONG)tolowerW(path[plen-3]) << 32);
1868
      if (ext == WCEXE || ext == WCBAT || ext == WCCMD || ext == WCCOM)
1869
        mode |= ALL_S_IEXEC;
1870 1871 1872 1873
    }
  }

  if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1874
    mode |= ALL_S_IWRITE;
1875 1876 1877

  buf->st_mode  = mode;
  buf->st_nlink = 1;
1878
  buf->st_size  = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
1879
  RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1880
  buf->st_atime = dw;
1881
  RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1882
  buf->st_mtime = buf->st_ctime = dw;
1883 1884
  TRACE("%d %d 0x%08lx%08lx %ld %ld %ld\n", buf->st_mode,buf->st_nlink,
        (long)(buf->st_size >> 32),(long)buf->st_size,
1885
        (long)buf->st_atime,(long)buf->st_mtime,(long)buf->st_ctime);
1886 1887 1888
  return 0;
}

1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
/*********************************************************************
 *		_wstati64 (MSVCRT.@)
 */
int CDECL MSVCRT__wstati64(const MSVCRT_wchar_t* path, struct MSVCRT__stati64 * buf)
{
  int ret;
  struct MSVCRT__stat64 buf64;

  ret = MSVCRT__wstat64(path, &buf64);
  if (!ret)
    msvcrt_stat64_to_stati64(&buf64, buf);
  return ret;
}

1903 1904 1905
/*********************************************************************
 *		_wstat (MSVCRT.@)
 */
1906
int CDECL MSVCRT__wstat(const MSVCRT_wchar_t* path, struct MSVCRT__stat * buf)
1907 1908
{
  int ret;
1909
  struct MSVCRT__stat64 buf64;
1910

1911 1912
  ret = MSVCRT__wstat64( path, &buf64 );
  if (!ret) msvcrt_stat64_to_stat(&buf64, buf);
1913 1914 1915
  return ret;
}

1916 1917 1918
/*********************************************************************
 *		_tell (MSVCRT.@)
 */
1919
long CDECL _tell(int fd)
1920
{
1921
  return _lseek(fd, 0, SEEK_CUR);
1922 1923
}

1924 1925 1926
/*********************************************************************
 *		_telli64 (MSVCRT.@)
 */
1927
__int64 CDECL _telli64(int fd)
1928 1929 1930 1931
{
  return _lseeki64(fd, 0, SEEK_CUR);
}

1932 1933 1934
/*********************************************************************
 *		_tempnam (MSVCRT.@)
 */
1935
char * CDECL _tempnam(const char *dir, const char *prefix)
1936 1937
{
  char tmpbuf[MAX_PATH];
1938 1939 1940
  const char *tmp_dir = MSVCRT_getenv("TMP");

  if (tmp_dir) dir = tmp_dir;
1941 1942 1943 1944 1945

  TRACE("dir (%s) prefix (%s)\n",dir,prefix);
  if (GetTempFileNameA(dir,prefix,0,tmpbuf))
  {
    TRACE("got name (%s)\n",tmpbuf);
1946
    DeleteFileA(tmpbuf);
1947
    return _strdup(tmpbuf);
1948
  }
1949
  TRACE("failed (%d)\n",GetLastError());
1950 1951 1952 1953 1954 1955
  return NULL;
}

/*********************************************************************
 *		_wtempnam (MSVCRT.@)
 */
1956
MSVCRT_wchar_t * CDECL _wtempnam(const MSVCRT_wchar_t *dir, const MSVCRT_wchar_t *prefix)
1957
{
1958
  MSVCRT_wchar_t tmpbuf[MAX_PATH];
1959 1960 1961 1962 1963

  TRACE("dir (%s) prefix (%s)\n",debugstr_w(dir),debugstr_w(prefix));
  if (GetTempFileNameW(dir,prefix,0,tmpbuf))
  {
    TRACE("got name (%s)\n",debugstr_w(tmpbuf));
1964
    DeleteFileW(tmpbuf);
1965
    return _wcsdup(tmpbuf);
1966
  }
1967
  TRACE("failed (%d)\n",GetLastError());
1968 1969 1970 1971 1972 1973
  return NULL;
}

/*********************************************************************
 *		_umask (MSVCRT.@)
 */
1974
int CDECL _umask(int umask)
1975 1976
{
  int old_umask = MSVCRT_umask;
1977
  TRACE("(%d)\n",umask);
1978 1979 1980 1981 1982 1983 1984
  MSVCRT_umask = umask;
  return old_umask;
}

/*********************************************************************
 *		_utime (MSVCRT.@)
 */
1985
int CDECL _utime(const char* path, struct MSVCRT__utimbuf *t)
1986
{
1987
  int fd = _open(path, MSVCRT__O_WRONLY | MSVCRT__O_BINARY);
1988 1989 1990

  if (fd > 0)
  {
1991 1992
    int retVal = _futime(fd, t);
    _close(fd);
1993 1994 1995 1996 1997
    return retVal;
  }
  return -1;
}

1998 1999 2000
/*********************************************************************
 *		_wutime (MSVCRT.@)
 */
2001
int CDECL _wutime(const MSVCRT_wchar_t* path, struct MSVCRT__utimbuf *t)
2002
{
2003
  int fd = _wopen(path, MSVCRT__O_WRONLY | MSVCRT__O_BINARY);
2004 2005 2006

  if (fd > 0)
  {
2007 2008
    int retVal = _futime(fd, t);
    _close(fd);
2009 2010 2011 2012 2013
    return retVal;
  }
  return -1;
}

2014 2015 2016
/*********************************************************************
 *		_write (MSVCRT.@)
 */
2017
int CDECL _write(int fd, const void* buf, unsigned int count)
2018 2019
{
  DWORD num_written;
2020
  HANDLE hand = msvcrt_fdtoh(fd);
2021

2022
  /* Don't trace small writes, it gets *very* annoying */
2023 2024 2025 2026
#if 0
  if (count > 32)
    TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
#endif
2027
  if (hand == INVALID_HANDLE_VALUE)
2028 2029 2030 2031
    {
      *MSVCRT__errno() = MSVCRT_EBADF;
      return -1;
    }
2032 2033

  /* If appending, go to EOF */
2034
  if (MSVCRT_fdesc[fd].wxflag & WX_APPEND)
2035
    _lseek(fd, 0, FILE_END);
2036

2037
  if (!(MSVCRT_fdesc[fd].wxflag & WX_TEXT))
2038 2039 2040 2041
    {
      if (WriteFile(hand, buf, count, &num_written, NULL)
	  &&  (num_written == count))
	return num_written;
2042
      TRACE("WriteFile (fd %d, hand %p) failed-last error (%d)\n", fd,
2043
       hand, GetLastError());
2044
      *MSVCRT__errno() = MSVCRT_ENOSPC;
2045 2046
    }
  else
2047 2048
  {
      unsigned int i, j, nr_lf;
2049 2050
      char *p = NULL;
      const char *q;
2051
      const char *s = (const char *)buf, *buf_start = (const char *)buf;
2052
      /* find number of \n ( without preceding \r ) */
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
      for ( nr_lf=0,i = 0; i <count; i++)
      {
          if (s[i]== '\n')
          {
              nr_lf++;
              /*if ((i >1) && (s[i-1] == '\r'))	nr_lf--; */
          }
      }
      if (nr_lf)
      {
2063
          if ((q = p = MSVCRT_malloc(count + nr_lf)))
2064
          {
2065
              for (s = (const char *)buf, i = 0, j = 0; i < count; i++)
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
              {
                  if (s[i]== '\n')
                  {
                      p[j++] = '\r';
                      /*if ((i >1) && (s[i-1] == '\r'))j--;*/
                  }
                  p[j++] = s[i];
              }
          }
          else
          {
              FIXME("Malloc failed\n");
              nr_lf =0;
2079
              q = buf;
2080 2081 2082
          }
      }
      else
2083
          q = buf;
2084

2085
      if ((WriteFile(hand, q, count+nr_lf, &num_written, NULL) == 0 ) || (num_written != count+nr_lf))
2086
      {
2087
          TRACE("WriteFile (fd %d, hand %p) failed-last error (%d), num_written %d\n",
2088
           fd, hand, GetLastError(), num_written);
2089 2090 2091 2092
          *MSVCRT__errno() = MSVCRT_ENOSPC;
          if(nr_lf)
              MSVCRT_free(p);
          return s - buf_start;
2093 2094 2095 2096 2097 2098 2099 2100
      }
      else
      {
          if(nr_lf)
              MSVCRT_free(p);
          return count;
      }
  }
2101 2102 2103 2104 2105 2106
  return -1;
}

/*********************************************************************
 *		_putw (MSVCRT.@)
 */
2107
int CDECL MSVCRT__putw(int val, MSVCRT_FILE* file)
2108
{
2109 2110 2111 2112 2113
  int len;
  len = _write(file->_file, &val, sizeof(val));
  if (len == sizeof(val)) return val;
  file->_flag |= MSVCRT__IOERR;
  return MSVCRT_EOF;
2114 2115 2116 2117 2118
}

/*********************************************************************
 *		fclose (MSVCRT.@)
 */
2119
int CDECL MSVCRT_fclose(MSVCRT_FILE* file)
2120
{
2121 2122 2123
  int r, flag;

  flag = file->_flag;
2124 2125
  MSVCRT_free(file->_tmpfname);
  file->_tmpfname = NULL;
2126 2127 2128 2129 2130 2131
  /* flush stdio buffers */
  if(file->_flag & MSVCRT__IOWRT)
      MSVCRT_fflush(file);
  if(file->_flag & MSVCRT__IOMYBUF)
      MSVCRT_free(file->_base);

2132
  r=_close(file->_file);
2133 2134 2135

  file->_flag = 0;

2136
  return ((r == -1) || (flag & MSVCRT__IOERR) ? MSVCRT_EOF : 0);
2137 2138 2139 2140 2141
}

/*********************************************************************
 *		feof (MSVCRT.@)
 */
2142
int CDECL MSVCRT_feof(MSVCRT_FILE* file)
2143
{
2144
  return file->_flag & MSVCRT__IOEOF;
2145 2146 2147 2148 2149
}

/*********************************************************************
 *		ferror (MSVCRT.@)
 */
2150
int CDECL MSVCRT_ferror(MSVCRT_FILE* file)
2151
{
2152
  return file->_flag & MSVCRT__IOERR;
2153 2154 2155 2156 2157
}

/*********************************************************************
 *		_filbuf (MSVCRT.@)
 */
2158
int CDECL MSVCRT__filbuf(MSVCRT_FILE* file)
2159
{
2160
  /* Allocate buffer if needed */
2161
  if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF) ) {
2162 2163
	msvcrt_alloc_buffer(file);
  }
2164 2165
  if(!(file->_flag & MSVCRT__IOREAD)) {
	if(file->_flag & MSVCRT__IORW) {
2166
		file->_flag |= MSVCRT__IOREAD;
2167
	} else {
2168 2169 2170
		return MSVCRT_EOF;
	}
  }
2171
  if(file->_flag & MSVCRT__IONBF) {
2172
	unsigned char c;
2173
        int r;
2174
  	if ((r = read_i(file->_file,&c,1)) != 1) {
2175 2176
            file->_flag |= (r == 0) ? MSVCRT__IOEOF : MSVCRT__IOERR;
            return MSVCRT_EOF;
2177 2178
	}
  	return c;
2179
  } else {
2180
	file->_cnt = read_i(file->_file, file->_base, file->_bufsiz);
2181 2182 2183 2184
	if(file->_cnt<=0) {
            file->_flag |= (file->_cnt == 0) ? MSVCRT__IOEOF : MSVCRT__IOERR;
            file->_cnt = 0;
            return MSVCRT_EOF;
2185 2186 2187 2188 2189
	}
	file->_cnt--;
	file->_ptr = file->_base+1;
	return *(unsigned char *)file->_base;
  }
2190 2191 2192
}

/*********************************************************************
2193
 *		fgetc (MSVCRT.@)
2194
 */
2195
int CDECL MSVCRT_fgetc(MSVCRT_FILE* file)
2196
{
2197 2198
  unsigned char *i;
  unsigned int j;
2199 2200 2201
  do {
    if (file->_cnt>0) {
      file->_cnt--;
2202
      i = (unsigned char *)file->_ptr++;
2203
      j = *i;
2204
    } else
2205 2206 2207 2208
      j = MSVCRT__filbuf(file);
    if (!(MSVCRT_fdesc[file->_file].wxflag & WX_TEXT) || (j != '\r'))
      return j;
  } while(1);
2209 2210 2211 2212 2213
}

/*********************************************************************
 *		_fgetchar (MSVCRT.@)
 */
2214
int CDECL _fgetchar(void)
2215 2216
{
  return MSVCRT_fgetc(MSVCRT_stdin);
2217 2218 2219 2220 2221
}

/*********************************************************************
 *		fgets (MSVCRT.@)
 */
2222
char * CDECL MSVCRT_fgets(char *s, int size, MSVCRT_FILE* file)
2223
{
2224
  int    cc = MSVCRT_EOF;
2225 2226 2227 2228 2229
  char * buf_start = s;

  TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
	file,file->_file,s,size);

2230
  while ((size >1) && (cc = MSVCRT_fgetc(file)) != MSVCRT_EOF && cc != '\n')
2231 2232
    {
      *s++ = (char)cc;
2233
      size --;
2234 2235 2236 2237
    }
  if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
  {
    TRACE(":nothing read\n");
2238
    return NULL;
2239
  }
2240 2241
  if ((cc != MSVCRT_EOF) && (size > 1))
    *s++ = cc;
2242
  *s = '\0';
Paul Rupe's avatar
Paul Rupe committed
2243
  TRACE(":got %s\n", debugstr_a(buf_start));
2244 2245 2246 2247 2248
  return buf_start;
}

/*********************************************************************
 *		fgetwc (MSVCRT.@)
2249
 *
2250
 * In MSVCRT__O_TEXT mode, multibyte characters are read from the file, dropping
2251
 * the CR from CR/LF combinations
2252
 */
2253
MSVCRT_wint_t CDECL MSVCRT_fgetwc(MSVCRT_FILE* file)
2254
{
2255 2256
  char c;

2257
  if (!(MSVCRT_fdesc[file->_file].wxflag & WX_TEXT))
2258 2259
    {
      MSVCRT_wchar_t wc;
2260 2261 2262 2263
      int i,j;
      char *chp, *wcp;
      wcp = (char *)&wc;
      for(i=0; i<sizeof(wc); i++)
2264
      {
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
        if (file->_cnt>0) 
        {
          file->_cnt--;
          chp = file->_ptr++;
          wcp[i] = *chp;
        } 
        else
        {
          j = MSVCRT__filbuf(file);
          if(file->_cnt<=0)
          {
            file->_flag |= (file->_cnt == 0) ? MSVCRT__IOEOF : MSVCRT__IOERR;
            file->_cnt = 0;
            return MSVCRT_WEOF;
          }
          wcp[i] = j;
        }
2282
      }
2283 2284
      return wc;
    }
2285
    
2286 2287 2288 2289 2290 2291
  c = MSVCRT_fgetc(file);
  if ((*__p___mb_cur_max() > 1) && MSVCRT_isleadbyte(c))
    {
      FIXME("Treat Multibyte characters\n");
    }
  if (c == MSVCRT_EOF)
2292
    return MSVCRT_WEOF;
2293 2294
  else
    return (MSVCRT_wint_t)c;
2295 2296
}

Duane Clark's avatar
Duane Clark committed
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
/*********************************************************************
 *		_getw (MSVCRT.@)
 */
int CDECL MSVCRT__getw(MSVCRT_FILE* file)
{
  char *ch;
  int i, j, k;
  ch = (char *)&i;
  for (j=0; j<sizeof(int); j++) {
    k = MSVCRT_fgetc(file);
    if (k == MSVCRT_EOF) {
      file->_flag |= MSVCRT__IOEOF;
      return EOF;
    }
    ch[j] = k;
  }
  return i;
}

2316 2317 2318
/*********************************************************************
 *		getwc (MSVCRT.@)
 */
2319
MSVCRT_wint_t CDECL MSVCRT_getwc(MSVCRT_FILE* file)
2320 2321 2322 2323 2324 2325 2326
{
  return MSVCRT_fgetwc(file);
}

/*********************************************************************
 *		_fgetwchar (MSVCRT.@)
 */
2327
MSVCRT_wint_t CDECL _fgetwchar(void)
2328 2329 2330 2331 2332 2333 2334
{
  return MSVCRT_fgetwc(MSVCRT_stdin);
}

/*********************************************************************
 *		getwchar (MSVCRT.@)
 */
2335
MSVCRT_wint_t CDECL MSVCRT_getwchar(void)
2336
{
2337
  return _fgetwchar();
2338 2339
}

2340 2341 2342
/*********************************************************************
 *              fgetws (MSVCRT.@)
 */
2343
MSVCRT_wchar_t * CDECL MSVCRT_fgetws(MSVCRT_wchar_t *s, int size, MSVCRT_FILE* file)
2344
{
2345
  int    cc = MSVCRT_WEOF;
2346
  MSVCRT_wchar_t * buf_start = s;
2347 2348 2349 2350

  TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
        file,file->_file,s,size);

2351
  while ((size >1) && (cc = MSVCRT_fgetwc(file)) != MSVCRT_WEOF && cc != '\n')
2352
    {
2353 2354
      *s++ = (char)cc;
      size --;
2355
    }
2356
  if ((cc == MSVCRT_WEOF) && (s == buf_start)) /* If nothing read, return 0*/
2357 2358
  {
    TRACE(":nothing read\n");
2359
    return NULL;
2360
  }
2361 2362 2363 2364
  if ((cc != MSVCRT_WEOF) && (size > 1))
    *s++ = cc;
  *s = 0;
  TRACE(":got %s\n", debugstr_w(buf_start));
2365 2366 2367
  return buf_start;
}

2368 2369 2370
/*********************************************************************
 *		fwrite (MSVCRT.@)
 */
2371
MSVCRT_size_t CDECL MSVCRT_fwrite(const void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383
{
  MSVCRT_size_t wrcnt=size * nmemb;
  int written = 0;
  if (size == 0)
      return 0;
  if(file->_cnt) {
	int pcnt=(file->_cnt>wrcnt)? wrcnt: file->_cnt;
	memcpy(file->_ptr, ptr, pcnt);
	file->_cnt -= pcnt;
	file->_ptr += pcnt;
	written = pcnt;
	wrcnt -= pcnt;
2384
        ptr = (const char*)ptr + pcnt;
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
  } else if(!(file->_flag & MSVCRT__IOWRT)) {
	if(file->_flag & MSVCRT__IORW) {
		file->_flag |= MSVCRT__IOWRT;
	} else
		return 0;
  }
  if(wrcnt) {
	/* Flush buffer */
  	int res=msvcrt_flush_buffer(file);
	if(!res) {
		int pwritten = _write(file->_file, ptr, wrcnt);
2396 2397 2398 2399 2400
  		if (pwritten <= 0)
                {
                    file->_flag |= MSVCRT__IOERR;
                    pwritten=0;
                }
2401 2402 2403 2404 2405
		written += pwritten;
	}
  }
  return written / size;
}
2406

2407 2408 2409
/*********************************************************************
 *		fputwc (MSVCRT.@)
 */
2410
MSVCRT_wint_t CDECL MSVCRT_fputwc(MSVCRT_wint_t wc, MSVCRT_FILE* file)
2411
{
2412
  MSVCRT_wchar_t mwc=wc;
2413
  if (MSVCRT_fwrite( &mwc, sizeof(mwc), 1, file) != 1)
2414 2415 2416 2417 2418 2419 2420
    return MSVCRT_WEOF;
  return wc;
}

/*********************************************************************
 *		_fputwchar (MSVCRT.@)
 */
2421
MSVCRT_wint_t CDECL _fputwchar(MSVCRT_wint_t wc)
2422 2423 2424 2425 2426
{
  return MSVCRT_fputwc(wc, MSVCRT_stdout);
}

/*********************************************************************
2427
 *		_fsopen (MSVCRT.@)
2428
 */
2429
MSVCRT_FILE * CDECL MSVCRT__fsopen(const char *path, const char *mode, int share)
2430 2431
{
  MSVCRT_FILE* file;
2432
  int open_flags, stream_flags, fd;
2433

2434
  TRACE("(%s,%s)\n",path,mode);
2435 2436

  /* map mode string to open() flags. "man fopen" for possibilities. */
2437 2438
  if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1)
      return NULL;
2439

2440
  LOCK_FILES();
2441
  fd = MSVCRT__sopen(path, open_flags, share, MSVCRT__S_IREAD | MSVCRT__S_IWRITE);
2442
  if (fd < 0)
2443 2444 2445
    file = NULL;
  else if ((file = msvcrt_alloc_fp()) && msvcrt_init_fp(file, fd, stream_flags)
   != -1)
2446 2447 2448 2449 2450 2451 2452
    TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,mode,file);
  else if (file)
  {
    file->_flag = 0;
    file = NULL;
  }

2453
  TRACE(":got (%p)\n",file);
2454
  if (fd >= 0 && !file)
2455
    _close(fd);
2456
  UNLOCK_FILES();
2457 2458 2459
  return file;
}

2460
/*********************************************************************
2461
 *		_wfsopen (MSVCRT.@)
2462
 */
2463
MSVCRT_FILE * CDECL MSVCRT__wfsopen(const MSVCRT_wchar_t *path, const MSVCRT_wchar_t *mode, int share)
2464
{
2465
  const unsigned int plen = strlenW(path), mlen = strlenW(mode);
2466 2467 2468 2469 2470 2471 2472 2473 2474
  char *patha = MSVCRT_calloc(plen + 1, 1);
  char *modea = MSVCRT_calloc(mlen + 1, 1);

  TRACE("(%s,%s)\n",debugstr_w(path),debugstr_w(mode));

  if (patha && modea &&
      WideCharToMultiByte(CP_ACP,0,path,plen,patha,plen,NULL,NULL) &&
      WideCharToMultiByte(CP_ACP,0,mode,mlen,modea,mlen,NULL,NULL))
  {
2475
    MSVCRT_FILE *retval = MSVCRT__fsopen(patha,modea,share);
2476 2477 2478 2479 2480
    MSVCRT_free(patha);
    MSVCRT_free(modea);
    return retval;
  }

2481
  msvcrt_set_errno(GetLastError());
2482 2483 2484
  return NULL;
}

2485
/*********************************************************************
2486
 *		fopen (MSVCRT.@)
2487
 */
2488
MSVCRT_FILE * CDECL MSVCRT_fopen(const char *path, const char *mode)
2489
{
2490
    return MSVCRT__fsopen( path, mode, MSVCRT__SH_DENYNO );
2491 2492
}

2493
/*********************************************************************
2494
 *		_wfopen (MSVCRT.@)
2495
 */
2496
MSVCRT_FILE * CDECL MSVCRT__wfopen(const MSVCRT_wchar_t *path, const MSVCRT_wchar_t *mode)
2497
{
2498
    return MSVCRT__wfsopen( path, mode, MSVCRT__SH_DENYNO );
2499 2500
}

2501
/* MSVCRT_fputc calls MSVCRT__flsbuf which calls MSVCRT_fputc */
2502
int CDECL MSVCRT__flsbuf(int c, MSVCRT_FILE* file);
2503

2504 2505 2506
/*********************************************************************
 *		fputc (MSVCRT.@)
 */
2507
int CDECL MSVCRT_fputc(int c, MSVCRT_FILE* file)
2508
{
2509
  if(file->_cnt>0) {
2510 2511 2512 2513 2514 2515 2516 2517 2518
    *file->_ptr++=c;
    file->_cnt--;
    if (c == '\n')
    {
      int res = msvcrt_flush_buffer(file);
      return res ? res : c;
    }
    else
      return c;
2519
  } else {
2520
    return MSVCRT__flsbuf(c, file);
2521
  }
2522 2523 2524 2525 2526
}

/*********************************************************************
 *		_flsbuf (MSVCRT.@)
 */
2527
int CDECL MSVCRT__flsbuf(int c, MSVCRT_FILE* file)
2528
{
2529 2530 2531 2532
  /* Flush output buffer */
  if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
	msvcrt_alloc_buffer(file);
  }
2533 2534
  if(!(file->_flag & MSVCRT__IOWRT)) {
	if(file->_flag & MSVCRT__IORW) {
2535
		file->_flag |= MSVCRT__IOWRT;
2536
	} else {
2537 2538 2539 2540 2541 2542
		return MSVCRT_EOF;
	}
  }
  if(file->_bufsiz) {
        int res=msvcrt_flush_buffer(file);
	return res?res : MSVCRT_fputc(c, file);
2543
  } else {
2544
	unsigned char cc=c;
2545 2546 2547 2548 2549
        int len;
  	len = _write(file->_file, &cc, 1);
        if (len == 1) return c;
        file->_flag |= MSVCRT__IOERR;
        return MSVCRT_EOF;
2550
  }
2551 2552 2553 2554 2555
}

/*********************************************************************
 *		_fputchar (MSVCRT.@)
 */
2556
int CDECL _fputchar(int c)
2557 2558 2559 2560 2561 2562 2563
{
  return MSVCRT_fputc(c, MSVCRT_stdout);
}

/*********************************************************************
 *		fread (MSVCRT.@)
 */
2564
MSVCRT_size_t CDECL MSVCRT_fread(void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
2565 2566 2567
{ MSVCRT_size_t rcnt=size * nmemb;
  MSVCRT_size_t read=0;
  int pread=0;
2568

2569 2570 2571
  if(!rcnt)
	return 0;

2572
  /* first buffered data */
2573
  if(file->_cnt>0) {
2574 2575 2576 2577
	int pcnt= (rcnt>file->_cnt)? file->_cnt:rcnt;
	memcpy(ptr, file->_ptr, pcnt);
	file->_cnt -= pcnt;
	file->_ptr += pcnt;
Duane Clark's avatar
Duane Clark committed
2578 2579
	if (MSVCRT_fdesc[file->_file].wxflag & WX_TEXT)
            pcnt -= remove_cr(ptr,pcnt);
2580 2581
	read += pcnt ;
	rcnt -= pcnt ;
2582
        ptr = (char*)ptr + pcnt;
2583 2584
  } else if(!(file->_flag & MSVCRT__IOREAD )) {
	if(file->_flag & MSVCRT__IORW) {
2585
		file->_flag |= MSVCRT__IOREAD;
2586
	} else
2587 2588
            return 0;
  }
Duane Clark's avatar
Duane Clark committed
2589
  while(rcnt>0)
2590
  {
2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604
    int i;
    /* Fill the buffer on small reads.
     * TODO: Use a better buffering strategy.
     */
    if (!file->_cnt && size*nmemb <= MSVCRT_BUFSIZ/2 && !(file->_flag & MSVCRT__IONBF)) {
      if (file->_bufsiz == 0) {
        msvcrt_alloc_buffer(file);
      }
      file->_cnt = _read(file->_file, file->_base, file->_bufsiz);
      file->_ptr = file->_base;
      i = (file->_cnt<rcnt) ? file->_cnt : rcnt;
      /* If the buffer fill reaches eof but fread wouldn't, clear eof. */
      if (i > 0 && i < file->_cnt) {
        MSVCRT_fdesc[file->_file].wxflag &= ~WX_ATEOF;
2605
        file->_flag &= ~MSVCRT__IOEOF;
2606 2607 2608 2609 2610 2611 2612 2613 2614
      }
      if (i > 0) {
        memcpy(ptr, file->_ptr, i);
        file->_cnt -= i;
        file->_ptr += i;
      }
    } else {
      i = _read(file->_file,ptr, rcnt);
    }
Duane Clark's avatar
Duane Clark committed
2615 2616
    pread += i;
    rcnt -= i;
2617
    ptr = (char *)ptr+i;
2618
    /* expose feof condition in the flags
2619
     * MFC tests file->_flag for feof, and doesn't call feof())
2620
     */
2621
    if ( MSVCRT_fdesc[file->_file].wxflag & WX_ATEOF)
2622
        file->_flag |= MSVCRT__IOEOF;
Duane Clark's avatar
Duane Clark committed
2623
    else if (i == -1)
2624 2625 2626
    {
        file->_flag |= MSVCRT__IOERR;
        pread = 0;
Duane Clark's avatar
Duane Clark committed
2627
        rcnt = 0;
2628
    }
2629
    if (i < 1) break;
2630 2631
  }
  read+=pread;
2632 2633 2634 2635 2636 2637 2638
  return read / size;
}

/*********************************************************************
 *		freopen (MSVCRT.@)
 *
 */
2639
MSVCRT_FILE* CDECL MSVCRT_freopen(const char *path, const char *mode,MSVCRT_FILE* file)
2640
{
2641
  int open_flags, stream_flags, fd;
2642 2643 2644

  TRACE(":path (%p) mode (%s) file (%p) fd (%d)\n",path,mode,file,file->_file);

2645 2646 2647 2648
  LOCK_FILES();
  if (!file || ((fd = file->_file) < 0) || fd > MSVCRT_fdend)
    file = NULL;
  else
2649
  {
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661
    MSVCRT_fclose(file);
    /* map mode string to open() flags. "man fopen" for possibilities. */
    if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1)
      file = NULL;
    else
    {
      fd = _open(path, open_flags, MSVCRT__S_IREAD | MSVCRT__S_IWRITE);
      if (fd < 0)
        file = NULL;
      else if (msvcrt_init_fp(file, fd, stream_flags) == -1)
      {
          file->_flag = 0;
2662
          WARN(":failed-last error (%d)\n",GetLastError());
2663 2664 2665 2666
          msvcrt_set_errno(GetLastError());
          file = NULL;
      }
    }
2667
  }
2668
  UNLOCK_FILES();
2669
  return file;
2670 2671 2672 2673 2674
}

/*********************************************************************
 *		fsetpos (MSVCRT.@)
 */
2675
int CDECL MSVCRT_fsetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
2676
{
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689
  /* Note that all this has been lifted 'as is' from fseek */
  if(file->_flag & MSVCRT__IOWRT)
	msvcrt_flush_buffer(file);

  /* Discard buffered input */
  file->_cnt = 0;
  file->_ptr = file->_base;
  
  /* Reset direction of i/o */
  if(file->_flag & MSVCRT__IORW) {
        file->_flag &= ~(MSVCRT__IOREAD|MSVCRT__IOWRT);
  }

2690
  return (_lseeki64(file->_file,*pos,SEEK_SET) == -1) ? -1 : 0;
2691 2692 2693 2694 2695
}

/*********************************************************************
 *		ftell (MSVCRT.@)
 */
2696
LONG CDECL MSVCRT_ftell(MSVCRT_FILE* file)
2697
{
2698 2699
  int off=0;
  long pos;
2700
  if(file->_bufsiz)  {
2701 2702
	if( file->_flag & MSVCRT__IOWRT ) {
		off = file->_ptr - file->_base;
2703
	} else {
2704 2705 2706 2707 2708 2709
		off = -file->_cnt;
	}
  }
  pos = _tell(file->_file);
  if(pos == -1) return pos;
  return off + pos;
2710 2711 2712
}

/*********************************************************************
2713
 *		fgetpos (MSVCRT.@)
2714
 */
2715
int CDECL MSVCRT_fgetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
2716
{
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
  /* This code has been lifted form the MSVCRT_ftell function */
  int off=0;

  *pos = _lseeki64(file->_file,0,SEEK_CUR);

  if (*pos == -1) return -1;
  
  if(file->_bufsiz)  {
	if( file->_flag & MSVCRT__IOWRT ) {
		off = file->_ptr - file->_base;
	} else {
		off = -file->_cnt;
	}
  }
  *pos += off;
  
  return 0;
2734 2735 2736 2737 2738
}

/*********************************************************************
 *		fputs (MSVCRT.@)
 */
2739
int CDECL MSVCRT_fputs(const char *s, MSVCRT_FILE* file)
2740
{
2741
    size_t i, len = strlen(s);
2742
    if (!(MSVCRT_fdesc[file->_file].wxflag & WX_TEXT))
2743 2744 2745 2746 2747
      return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
    for (i=0; i<len; i++)
      if (MSVCRT_fputc(s[i], file) == MSVCRT_EOF) 
	return MSVCRT_EOF;
    return 0;
2748 2749
}

2750 2751 2752
/*********************************************************************
 *		fputws (MSVCRT.@)
 */
2753
int CDECL MSVCRT_fputws(const MSVCRT_wchar_t *s, MSVCRT_FILE* file)
2754
{
2755
    size_t i, len = strlenW(s);
2756
    if (!(MSVCRT_fdesc[file->_file].wxflag & WX_TEXT))
2757 2758 2759 2760 2761 2762 2763 2764 2765
      return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
    for (i=0; i<len; i++)
      {
	if ((s[i] == L'\n') && (MSVCRT_fputc('\r', file) == MSVCRT_EOF))
	  return MSVCRT_WEOF;
	if (MSVCRT_fputwc(s[i], file) == MSVCRT_WEOF)
	  return MSVCRT_WEOF; 
      }
    return 0;
2766 2767
}

2768 2769 2770
/*********************************************************************
 *		getchar (MSVCRT.@)
 */
2771
int CDECL MSVCRT_getchar(void)
2772 2773 2774 2775 2776 2777 2778
{
  return MSVCRT_fgetc(MSVCRT_stdin);
}

/*********************************************************************
 *		getc (MSVCRT.@)
 */
2779
int CDECL MSVCRT_getc(MSVCRT_FILE* file)
2780 2781 2782 2783 2784 2785 2786
{
  return MSVCRT_fgetc(file);
}

/*********************************************************************
 *		gets (MSVCRT.@)
 */
2787
char * CDECL MSVCRT_gets(char *buf)
2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
{
  int    cc;
  char * buf_start = buf;

  for(cc = MSVCRT_fgetc(MSVCRT_stdin); cc != MSVCRT_EOF && cc != '\n';
      cc = MSVCRT_fgetc(MSVCRT_stdin))
  if(cc != '\r') *buf++ = (char)cc;

  *buf = '\0';

  TRACE("got '%s'\n", buf_start);
  return buf_start;
}

Francois Gouget's avatar
Francois Gouget committed
2802 2803 2804
/*********************************************************************
 *		_getws (MSVCRT.@)
 */
2805
MSVCRT_wchar_t* CDECL MSVCRT__getws(MSVCRT_wchar_t* buf)
Francois Gouget's avatar
Francois Gouget committed
2806 2807
{
    MSVCRT_wint_t cc;
2808
    MSVCRT_wchar_t* ws = buf;
Francois Gouget's avatar
Francois Gouget committed
2809 2810 2811 2812 2813

    for (cc = MSVCRT_fgetwc(MSVCRT_stdin); cc != MSVCRT_WEOF && cc != '\n';
         cc = MSVCRT_fgetwc(MSVCRT_stdin))
    {
        if (cc != '\r')
2814
            *buf++ = (MSVCRT_wchar_t)cc;
Francois Gouget's avatar
Francois Gouget committed
2815 2816 2817
    }
    *buf = '\0';

2818
    TRACE("got %s\n", debugstr_w(ws));
Francois Gouget's avatar
Francois Gouget committed
2819 2820 2821
    return ws;
}

2822 2823 2824
/*********************************************************************
 *		putc (MSVCRT.@)
 */
2825
int CDECL MSVCRT_putc(int c, MSVCRT_FILE* file)
2826 2827 2828 2829 2830 2831 2832
{
  return MSVCRT_fputc(c, file);
}

/*********************************************************************
 *		putchar (MSVCRT.@)
 */
2833
int CDECL MSVCRT_putchar(int c)
2834
{
2835
  return MSVCRT_fputc(c, MSVCRT_stdout);
2836 2837 2838 2839 2840
}

/*********************************************************************
 *		puts (MSVCRT.@)
 */
2841
int CDECL MSVCRT_puts(const char *s)
2842
{
2843 2844
    size_t len = strlen(s);
    if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
2845 2846 2847
    return MSVCRT_fwrite("\n",1,1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
}

2848 2849 2850
/*********************************************************************
 *		_putws (MSVCRT.@)
 */
2851
int CDECL _putws(const MSVCRT_wchar_t *s)
2852
{
2853
    static const MSVCRT_wchar_t nl = '\n';
2854 2855
    size_t len = strlenW(s);
    if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
2856 2857 2858
    return MSVCRT_fwrite(&nl,sizeof(nl),1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
}

2859 2860 2861
/*********************************************************************
 *		remove (MSVCRT.@)
 */
2862
int CDECL MSVCRT_remove(const char *path)
2863
{
2864
  TRACE("(%s)\n",path);
2865 2866
  if (DeleteFileA(path))
    return 0;
2867
  TRACE(":failed (%d)\n",GetLastError());
2868
  msvcrt_set_errno(GetLastError());
2869 2870 2871 2872 2873 2874
  return -1;
}

/*********************************************************************
 *		_wremove (MSVCRT.@)
 */
2875
int CDECL _wremove(const MSVCRT_wchar_t *path)
2876 2877 2878 2879
{
  TRACE("(%s)\n",debugstr_w(path));
  if (DeleteFileW(path))
    return 0;
2880
  TRACE(":failed (%d)\n",GetLastError());
2881
  msvcrt_set_errno(GetLastError());
2882 2883 2884 2885 2886 2887
  return -1;
}

/*********************************************************************
 *		rename (MSVCRT.@)
 */
2888
int CDECL MSVCRT_rename(const char *oldpath,const char *newpath)
2889 2890
{
  TRACE(":from %s to %s\n",oldpath,newpath);
2891
  if (MoveFileExA(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
2892
    return 0;
2893
  TRACE(":failed (%d)\n",GetLastError());
2894
  msvcrt_set_errno(GetLastError());
2895 2896 2897
  return -1;
}

2898 2899 2900
/*********************************************************************
 *		_wrename (MSVCRT.@)
 */
2901
int CDECL _wrename(const MSVCRT_wchar_t *oldpath,const MSVCRT_wchar_t *newpath)
2902 2903
{
  TRACE(":from %s to %s\n",debugstr_w(oldpath),debugstr_w(newpath));
2904
  if (MoveFileExW(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
2905
    return 0;
2906
  TRACE(":failed (%d)\n",GetLastError());
2907
  msvcrt_set_errno(GetLastError());
2908 2909 2910 2911 2912 2913
  return -1;
}

/*********************************************************************
 *		setvbuf (MSVCRT.@)
 */
2914
int CDECL MSVCRT_setvbuf(MSVCRT_FILE* file, char *buf, int mode, MSVCRT_size_t size)
2915
{
2916
  /* TODO: Check if file busy */
2917
  if(file->_bufsiz) {
2918 2919 2920 2921
	MSVCRT_free(file->_base);
	file->_bufsiz = 0;
	file->_cnt = 0;
  }
2922
  if(mode == MSVCRT__IOFBF) {
2923 2924
	file->_flag &= ~MSVCRT__IONBF;
  	file->_base = file->_ptr = buf;
2925
  	if(buf) {
2926
		file->_bufsiz = size;
2927
	}
2928 2929 2930 2931
  } else {
	file->_flag |= MSVCRT__IONBF;
  }
  return 0;
2932 2933
}

2934 2935 2936
/*********************************************************************
 *		setbuf (MSVCRT.@)
 */
2937
void CDECL MSVCRT_setbuf(MSVCRT_FILE* file, char *buf)
2938
{
2939
  MSVCRT_setvbuf(file, buf, buf ? MSVCRT__IOFBF : MSVCRT__IONBF, MSVCRT_BUFSIZ);
2940 2941 2942 2943 2944
}

/*********************************************************************
 *		tmpnam (MSVCRT.@)
 */
2945
char * CDECL MSVCRT_tmpnam(char *s)
2946
{
2947 2948 2949 2950 2951 2952 2953 2954 2955
  static int unique;
  char tmpstr[16];
  char *p;
  int count;
  if (s == 0)
    s = MSVCRT_tmpname;
  msvcrt_int_to_base32(GetCurrentProcessId(), tmpstr);
  p = s + sprintf(s, "\\s%s.", tmpstr);
  for (count = 0; count < MSVCRT_TMP_MAX; count++)
2956
  {
2957 2958 2959 2960 2961
    msvcrt_int_to_base32(unique++, tmpstr);
    strcpy(p, tmpstr);
    if (GetFileAttributesA(s) == INVALID_FILE_ATTRIBUTES &&
        GetLastError() == ERROR_FILE_NOT_FOUND)
      break;
2962 2963 2964 2965 2966 2967 2968
  }
  return s;
}

/*********************************************************************
 *		tmpfile (MSVCRT.@)
 */
2969
MSVCRT_FILE* CDECL MSVCRT_tmpfile(void)
2970 2971 2972
{
  char *filename = MSVCRT_tmpnam(NULL);
  int fd;
2973 2974
  MSVCRT_FILE* file = NULL;

2975
  LOCK_FILES();
2976
  fd = _open(filename, MSVCRT__O_CREAT | MSVCRT__O_BINARY | MSVCRT__O_RDWR | MSVCRT__O_TEMPORARY);
2977 2978
  if (fd != -1 && (file = msvcrt_alloc_fp()))
  {
2979
    if (msvcrt_init_fp(file, fd, MSVCRT__O_RDWR) == -1)
2980 2981 2982 2983 2984 2985
    {
        file->_flag = 0;
        file = NULL;
    }
    else file->_tmpfname = _strdup(filename);
  }
2986
  UNLOCK_FILES();
2987
  return file;
2988 2989 2990 2991 2992
}

/*********************************************************************
 *		vfprintf (MSVCRT.@)
 */
2993
int CDECL MSVCRT_vfprintf(MSVCRT_FILE* file, const char *format, va_list valist)
2994 2995
{
  char buf[2048], *mem = buf;
2996
  int written, resize = sizeof(buf), retval;
2997 2998 2999 3000 3001
  /* There are two conventions for vsnprintf failing:
   * Return -1 if we truncated, or
   * Return the number of bytes that would have been written
   * The code below handles both cases
   */
3002
  while ((written = MSVCRT_vsnprintf(mem, resize, format, valist)) == -1 ||
3003 3004 3005 3006 3007 3008 3009 3010
          written > resize)
  {
    resize = (written == -1 ? resize * 2 : written + 1);
    if (mem != buf)
      MSVCRT_free (mem);
    if (!(mem = (char *)MSVCRT_malloc(resize)))
      return MSVCRT_EOF;
  }
3011
  retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
3012 3013
  if (mem != buf)
    MSVCRT_free (mem);
3014 3015 3016 3017 3018
  return retval;
}

/*********************************************************************
 *		vfwprintf (MSVCRT.@)
3019
 * FIXME:
3020 3021
 * Is final char included in written (then resize is too big) or not
 * (then we must test for equality too)?
3022
 */
3023
int CDECL MSVCRT_vfwprintf(MSVCRT_FILE* file, const MSVCRT_wchar_t *format, va_list valist)
3024
{
3025 3026
  MSVCRT_wchar_t buf[2048], *mem = buf;
  int written, resize = sizeof(buf) / sizeof(MSVCRT_wchar_t), retval;
3027
  /* See vfprintf comments */
3028
  while ((written = MSVCRT_vsnwprintf(mem, resize, format, valist)) == -1 ||
3029 3030
          written > resize)
  {
3031
    resize = (written == -1 ? resize * 2 : written + sizeof(MSVCRT_wchar_t));
3032 3033
    if (mem != buf)
      MSVCRT_free (mem);
3034
    if (!(mem = (MSVCRT_wchar_t *)MSVCRT_malloc(resize*sizeof(*mem))))
3035 3036
      return MSVCRT_EOF;
  }
3037
  retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
3038 3039 3040 3041 3042 3043 3044 3045
  if (mem != buf)
    MSVCRT_free (mem);
  return retval;
}

/*********************************************************************
 *		vprintf (MSVCRT.@)
 */
3046
int CDECL MSVCRT_vprintf(const char *format, va_list valist)
3047 3048 3049 3050 3051 3052 3053
{
  return MSVCRT_vfprintf(MSVCRT_stdout,format,valist);
}

/*********************************************************************
 *		vwprintf (MSVCRT.@)
 */
3054
int CDECL MSVCRT_vwprintf(const MSVCRT_wchar_t *format, va_list valist)
3055 3056
{
  return MSVCRT_vfwprintf(MSVCRT_stdout,format,valist);
3057 3058 3059 3060 3061
}

/*********************************************************************
 *		fprintf (MSVCRT.@)
 */
3062
int CDECL MSVCRT_fprintf(MSVCRT_FILE* file, const char *format, ...)
3063 3064 3065 3066 3067 3068 3069 3070 3071
{
    va_list valist;
    int res;
    va_start(valist, format);
    res = MSVCRT_vfprintf(file, format, valist);
    va_end(valist);
    return res;
}

3072 3073 3074
/*********************************************************************
 *		fwprintf (MSVCRT.@)
 */
3075
int CDECL MSVCRT_fwprintf(MSVCRT_FILE* file, const MSVCRT_wchar_t *format, ...)
3076 3077 3078 3079 3080 3081 3082 3083 3084
{
    va_list valist;
    int res;
    va_start(valist, format);
    res = MSVCRT_vfwprintf(file, format, valist);
    va_end(valist);
    return res;
}

3085 3086 3087
/*********************************************************************
 *		printf (MSVCRT.@)
 */
3088
int CDECL MSVCRT_printf(const char *format, ...)
3089 3090 3091 3092 3093 3094 3095 3096 3097
{
    va_list valist;
    int res;
    va_start(valist, format);
    res = MSVCRT_vfprintf(MSVCRT_stdout, format, valist);
    va_end(valist);
    return res;
}

3098 3099 3100
/*********************************************************************
 *		ungetc (MSVCRT.@)
 */
3101
int CDECL MSVCRT_ungetc(int c, MSVCRT_FILE * file)
3102
{
Paul Rupe's avatar
Paul Rupe committed
3103 3104
	if (c == MSVCRT_EOF)
		return MSVCRT_EOF;
3105
	if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
3106 3107 3108
		msvcrt_alloc_buffer(file);
		file->_ptr++;
	}
3109
	if(file->_ptr>file->_base) {
3110 3111 3112
		file->_ptr--;
		*file->_ptr=c;
		file->_cnt++;
Paul Rupe's avatar
Paul Rupe committed
3113
		MSVCRT_clearerr(file);
3114 3115 3116 3117 3118 3119 3120 3121
		return c;
	}
	return MSVCRT_EOF;
}

/*********************************************************************
 *              ungetwc (MSVCRT.@)
 */
3122
MSVCRT_wint_t CDECL MSVCRT_ungetwc(MSVCRT_wint_t wc, MSVCRT_FILE * file)
3123
{
3124
	MSVCRT_wchar_t mwc = wc;
3125 3126
	char * pp = (char *)&mwc;
	int i;
3127
	for(i=sizeof(MSVCRT_wchar_t)-1;i>=0;i--) {
3128 3129 3130 3131 3132 3133
		if(pp[i] != MSVCRT_ungetc(pp[i],file))
			return MSVCRT_WEOF;
	}
	return mwc;
}

3134 3135 3136
/*********************************************************************
 *		wprintf (MSVCRT.@)
 */
3137
int CDECL MSVCRT_wprintf(const MSVCRT_wchar_t *format, ...)
3138 3139 3140 3141 3142 3143 3144 3145
{
    va_list valist;
    int res;
    va_start(valist, format);
    res = MSVCRT_vwprintf(format, valist);
    va_end(valist);
    return res;
}
3146

3147 3148 3149 3150 3151 3152 3153 3154 3155
/*********************************************************************
 *		_getmaxstdio (MSVCRT.@)
 */
int CDECL _getmaxstdio(void)
{
    FIXME("stub, always returns 512\n");
    return 512;
}

3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169
/*********************************************************************
 *		_setmaxstdio_ (MSVCRT.@)
 */
int CDECL _setmaxstdio(int newmax)
{
    int res;
    if( newmax > 2048)
      res = -1;
    else
      res = newmax;
    FIXME("stub: setting new maximum for number of simultaneously open files not implemented,returning %d\n",res);
    return res;
}

3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
/*********************************************************************
 *		__pioinfo (MSVCRT.@)
 * FIXME: see MSVCRT_MAX_FILES define.
 */
ioinfo * MSVCRT___pioinfo[] = { /* array of pointers to ioinfo arrays [64] */
    &MSVCRT_fdesc[0 * 64], &MSVCRT_fdesc[1 * 64], &MSVCRT_fdesc[2 * 64],
    &MSVCRT_fdesc[3 * 64], &MSVCRT_fdesc[4 * 64], &MSVCRT_fdesc[5 * 64],
    &MSVCRT_fdesc[6 * 64], &MSVCRT_fdesc[7 * 64], &MSVCRT_fdesc[8 * 64],
    &MSVCRT_fdesc[9 * 64], &MSVCRT_fdesc[10 * 64], &MSVCRT_fdesc[11 * 64],
    &MSVCRT_fdesc[12 * 64], &MSVCRT_fdesc[13 * 64], &MSVCRT_fdesc[14 * 64],
    &MSVCRT_fdesc[15 * 64], &MSVCRT_fdesc[16 * 64], &MSVCRT_fdesc[17 * 64],
    &MSVCRT_fdesc[18 * 64], &MSVCRT_fdesc[19 * 64], &MSVCRT_fdesc[20 * 64],
    &MSVCRT_fdesc[21 * 64], &MSVCRT_fdesc[22 * 64], &MSVCRT_fdesc[23 * 64],
    &MSVCRT_fdesc[24 * 64], &MSVCRT_fdesc[25 * 64], &MSVCRT_fdesc[26 * 64],
    &MSVCRT_fdesc[27 * 64], &MSVCRT_fdesc[28 * 64], &MSVCRT_fdesc[29 * 64],
    &MSVCRT_fdesc[30 * 64], &MSVCRT_fdesc[31 * 64]
} ;

/*********************************************************************
 *		__badioinfo (MSVCRT.@)
 */
ioinfo MSVCRT___badioinfo = { INVALID_HANDLE_VALUE, WX_TEXT };