int32_t omrfile_set_length(struct OMRPortLibrary *portLibrary, intptr_t fd, int64_t newLength) { int32_t lastError = 0; int64_t currentFilePtr = 0; Trc_PRT_file_setlength_Entry(fd, newLength); /* Save current file pointer location */ currentFilePtr = omrfile_seek(portLibrary, fd, 0, EsSeekCur); if ((-1 != currentFilePtr) && (-1 != omrfile_seek(portLibrary, fd, newLength, FILE_BEGIN))) { if (0 == SetEndOfFile((HANDLE)fd)) { lastError = GetLastError(); lastError = portLibrary->error_set_last_error(portLibrary, lastError, findError(lastError)); Trc_PRT_file_setlength_Exit(lastError); return lastError; } /* Put pointer back to where it started */ if (-1 != omrfile_seek(portLibrary, fd, currentFilePtr, EsSeekSet)) { Trc_PRT_file_setlength_Exit(0); return 0; } } /* omrfile_seek already set the last error */ lastError = portLibrary->error_last_error_number(portLibrary); Trc_PRT_file_setlength_Exit(lastError); return lastError; }
/** * Set the length of a file to a specified value. * * @param[in] portLibrary The port library * @param[in] fd The file descriptor. * @param[in] newLength Length to be set * * @return 0 on success, negative portable error code on failure */ int32_t omrfile_set_length(struct OMRPortLibrary *portLibrary, intptr_t inFD, int64_t newLength) { int fd = (int)inFD; int32_t rc; off_t length = (off_t)newLength; Trc_PRT_file_setlength_Entry(inFD, newLength); /* If file offsets are 32 bit, truncate the newLength to that range */ if (sizeof(off_t) < sizeof(int64_t)) { if (newLength > 0x7FFFFFFF) { length = 0x7FFFFFFF; } else if (newLength < -0x7FFFFFFF) { length = -0x7FFFFFFF; } } #if (FD_BIAS != 0) if (fd < FD_BIAS) { /* Cannot ftruncate on STD streams, and no other FD's should exist <FD_BIAS */ Trc_PRT_file_setlength_Exit(-1); return -1; } #endif rc = ftruncate(fd - FD_BIAS, length); if (0 != rc) { rc = portLibrary->error_set_last_error(portLibrary, errno, findError(errno)); } Trc_PRT_file_setlength_Exit(rc); return rc; }