Пример #1
1
/**
 * this function tries to make a particular range of a file allocated (corresponding to disk space)
 * it is advisory, and the range specified in the arguments will never contain live data
 */
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
#if defined(WIN32)
    // Windows-specific version
    HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
    LARGE_INTEGER nFileSize;
    int64_t nEndPos = (int64_t)offset + length;
    nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
    nFileSize.u.HighPart = nEndPos >> 32;
    SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
    SetEndOfFile(hFile);
#elif defined(MAC_OSX)
    // OSX specific version
    fstore_t fst;
    fst.fst_flags = F_ALLOCATECONTIG;
    fst.fst_posmode = F_PEOFPOSMODE;
    fst.fst_offset = 0;
    fst.fst_length = (off_t)offset + length;
    fst.fst_bytesalloc = 0;
    if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
        fst.fst_flags = F_ALLOCATEALL;
        fcntl(fileno(file), F_PREALLOCATE, &fst);
    }
    ftruncate(fileno(file), fst.fst_length);
#elif defined(__linux__)
    // Version using posix_fallocate
    off_t nEndPos = (off_t)offset + length;
    posix_fallocate(fileno(file), 0, nEndPos);
#else
    // Fallback version
    // TODO: just write one byte per block
    static const char buf[65536] = {};
    if (fseek(file, offset, SEEK_SET)) {
        return;
    }
    while (length > 0) {
        unsigned int now = 65536;
        if (length < now)
            now = length;
        fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
        length -= now;
    }
#endif
}
CMappedMemory::~CMappedMemory()
{
	if (m_Base)
	{
		myFlushViewOfFile(m_Base, NULL);
		myUnmapViewOfFile(m_Base);
	}
	if (m_FileMapping)
		CloseHandle(m_FileMapping);
	
	if (m_DirectFile)
	{
		if (INVALID_SET_FILE_POINTER != SetFilePointer(m_DirectFile, m_Size, NULL, FILE_BEGIN))
			SetEndOfFile(m_DirectFile);

		FlushFileBuffers(m_DirectFile);
		CloseHandle(m_DirectFile);
	}
}
Пример #3
0
ALERROR CTextFileLog::Create (BOOL bAppend)

//	Create
//
//	Create a new log file

	{
	ASSERT(m_hFile == NULL);

	m_hFile = CreateFile(m_sFilename.GetASCIIZPointer(),
			GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_READ,
			NULL,
			OPEN_ALWAYS,
			FILE_ATTRIBUTE_NORMAL,
			NULL);
	if (m_hFile == INVALID_HANDLE_VALUE)
		{
		DWORD dwError = ::GetLastError();
		m_hFile = NULL;
		return ERR_FAIL;
		}

	//	If we're appending to an existing log file, move the file pointer
	//	to the end of the file.

	if (bAppend)
		{
		LONG lFileHigh = 0;
		m_dwSessionStart = ::SetFilePointer(m_hFile, 0, &lFileHigh, FILE_END);
		}

	//	Otherwise, truncate the file

	else
		{
		SetFilePointer(m_hFile, 0, NULL, FILE_BEGIN);
		SetEndOfFile(m_hFile);
		m_dwSessionStart = 0;
		}

	return NOERROR;
	}
Пример #4
0
	// win32 ftruncate emulation using lseek then
	// setting endoffile position
	int como__ftruncate (int fd, long pos){
		if ( lseek(fd, pos, SEEK_SET) < 0 ){
			return -1;
		}

		int handle = _get_osfhandle(fd);

		if (handle == -1){
			errno = EBADF;
			return -1;
		}

		if (SetEndOfFile((HANDLE)handle) == 0){
			errno = GetLastError();
			return -1;
		}

		return 0;
	}
Пример #5
0
/*----------------------------------------------------------------------------------------------
	Set the size of the stream. Here, this means setting the file pointer to the new size
	and then setting EOF to the position of the file pointer. Note that the stream seek pointer
	is not affected by this method. Note also that SetEndOfFile() fails unless we have write
	access to the file.
----------------------------------------------------------------------------------------------*/
STDMETHODIMP FileStream::SetSize(ULARGE_INTEGER libNewSize)
{
	BEGIN_COM_METHOD;
	if (libNewSize.QuadPart < 0)
		ThrowHr(WarnHr(STG_E_INVALIDPARAMETER));

	DWORD dwLow;
	long dwHigh = (long)libNewSize.HighPart;
	// Could check for write access before going further, but setting the file pointer
	// doesn't really do any harm so we may as well let it go on and fail later if it is
	// going to.
	dwLow = SetFilePointer(m_hfile, libNewSize.LowPart, &dwHigh, FILE_BEGIN);
	if (dwLow == 0xFFFFFFFF && GetLastError() != NO_ERROR)
		ThrowHr(WarnHr(STG_E_SEEKERROR));
	if (!SetEndOfFile(m_hfile))
		ThrowHr(WarnHr(STG_E_ACCESSDENIED)); // probably the right error code

	END_COM_METHOD(g_fact, IID_IStream);
}
Пример #6
0
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
bool create_very_big_file(_In_ const wchar_t* file_path, _In_ uint64_t size_in_mb)
{
	_ASSERTE(NULL != file_path);
	if (NULL == file_path) return false;

	if (is_file_existsW(file_path))
	{
		::DeleteFileW(file_path);
	}

	// create very big file
	HANDLE file_handle = CreateFile(
		file_path,
		GENERIC_WRITE,
		FILE_SHARE_READ,
		NULL,
		CREATE_NEW,
		FILE_ATTRIBUTE_NORMAL,
		NULL
		);
	if (INVALID_HANDLE_VALUE == file_handle)
	{
		print("err ] CreateFile( %ws ) failed. gle = %u", file_path, GetLastError());
		return false;
	}

	LARGE_INTEGER file_size = { 0 };
	//file_size.LowPart = 0;
	//file_size.HighPart = 1;
	file_size.QuadPart = (1024 * 1024) * size_in_mb;

	if (!SetFilePointerEx(file_handle, file_size, NULL, FILE_BEGIN))
	{
		print("err ] SetFilePointerEx() failed. gle = %u", GetLastError());

		CloseHandle(file_handle);
		return false;
	}

	SetEndOfFile(file_handle);
	CloseHandle(file_handle);
	return true;
}
Пример #7
0
File::File(char *pFileName, int length) {

   DWORD ret = 0;

   /* Make a copy of the filename */
   strncpy(fileName, pFileName, MAX_PATH);

   hFile = INVALID_HANDLE_VALUE;

   /* Open the file - Note its opened write, shared read, and RANDOM_ACCESS since 
      we are going to be jumping around alot */

   hFile = CreateFile(fileName, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
            OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, NULL);

   if (hFile == INVALID_HANDLE_VALUE) {
      ret = GetLastError();
      throwError(fileName, ret);
   }

   /* Now make sure the file is the correct length */
   ret = SetFilePointer(hFile, (DWORD) length, NULL, FILE_BEGIN);
   
   if (ret == INVALID_SET_FILE_POINTER) {
      ret = GetLastError();
      CloseHandle(hFile);
      hFile = NULL;
      throwError(fileName, ret);
   }

   /* Now save the file as this length */
   ret = SetEndOfFile(hFile);

   if (ret==0) {
      ret = GetLastError();   
      CloseHandle(hFile);
      hFile = NULL;
      throwError(fileName, ret);
   }
   
   /* Initialize the critical section */
   InitializeCriticalSection (&fileLock);
}
Пример #8
0
BOOL PrunnedFileViewer::Show(LPCTSTR description)
{
	if (m_hFile == INVALID_HANDLE_VALUE)
		return FALSE;

	CThreadLock lock(&m_cs, TRUE);

	DWORD dwPtr = SetFilePointer(m_hFile, 0, 0, FILE_BEGIN);
	if (dwPtr == INVALID_SET_FILE_POINTER)
	{
		DWORD dwError = GetLastError();
		if (dwError != NO_ERROR)
			return FALSE;
	}
	if (SetEndOfFile(m_hFile) == 0)
	{
		DWORD dwError = GetLastError();
		if (dwError != NO_ERROR)
			return FALSE;
	}
	while (m_debugLines.size() >= m_maxLines)
		m_debugLines.pop_front();
	WideCharToMultiByte(CP_ACP, NULL, description, -1, bf, cbfLen, 0,0);
	DWORD le = GetLastError();
	m_debugLines.push_back(bf);//Gives a ERROR_INVALID_HANDLE (6)
	if (le != GetLastError())
		SetLastError(le);
	std::list<std::string>::const_iterator it = m_debugLines.begin();
	DWORD bytesWritten = 0;
	while (it != m_debugLines.end())
	{
		DWORD bytesWritten = 0;
		const std::string& str = *it;
		if (!WriteFile(m_hFile, (LPCSTR)str.c_str(), (DWORD)str.size(), &bytesWritten, NULL))
		{
			CloseHandle(m_hFile);
			m_hFile = INVALID_HANDLE_VALUE;
			return FALSE;//FlushFileBuffers(m_hFile);
		}
		it++;
	}
	return TRUE;
}
Пример #9
0
void CheckFileSize(HANDLE hFile, DWORD dwOffset, DWORD dwHighOrder)
{
    DWORD dwRc = 0;
    DWORD dwError = 0;
    LARGE_INTEGER qwFileSize;

    dwRc = SetFilePointer(hFile, dwOffset, (PLONG)&dwHighOrder, FILE_BEGIN);
    if (dwRc == INVALID_SET_FILE_POINTER)
    {
        Trace("GetFileSizeEx: ERROR -> Call to SetFilePointer failed with %ld.\n", 
            GetLastError());
        CleanUp(hFile);
        Fail("");
    }
    else
    {
        if (!SetEndOfFile(hFile))
        {
            dwError = GetLastError();
            CleanUp(hFile);
            if (dwError == 112)
            {
                Fail("GetFileSizeEx: ERROR -> SetEndOfFile failed due to lack of "
                    "disk space\n");
            }
            else
            {
                Fail("GetFileSizeEx: ERROR -> SetEndOfFile call failed "
                    "with error %ld\n", dwError);
            }
        }
        else
        {
            GetFileSizeEx(hFile, &qwFileSize);
            if ((qwFileSize.u.LowPart != dwOffset) || 
                (qwFileSize.u.HighPart != dwHighOrder))
            {
                CleanUp(hFile);
                Fail("GetFileSizeEx: ERROR -> File sizes do not match up.\n");
            }
        }
    }
}
Пример #10
0
int truncate(const char *path, long length)
{
    HANDLE file = CreateFile(path, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 
    				FILE_SHARE_WRITE | FILE_SHARE_READ, NULL);
	
    if (file == INVALID_HANDLE_VALUE)
    {
		return -1;
    }
	
    if (SetFilePointer(file, length, NULL, FILE_BEGIN) == 0xFFFFFFFF || !SetEndOfFile(file))
    {
		CloseHandle(file);
		return -1;
    }
	
    CloseHandle(file);
    return 0;
}
Пример #11
0
// Save recorded speech to file
int SaveRecordtoFile(const char* fileName, WAVEFORMATEX* wf, HWAVEIN* hWaveIn, WAVEHDR* waveHeader, MMTIME* mmTime)
{
	int res;
	DWORD NumToWrite=0;
	DWORD dwNumber = 0;

	waveHeader->dwBytesRecorded = mmTime->u.cb;
	
	HANDLE FileHandle = CreateFile( CString(fileName), GENERIC_WRITE, 
		FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

	dwNumber = FCC("RIFF");
	WriteFile(FileHandle, &dwNumber, 4, &NumToWrite, NULL);

	dwNumber = waveHeader->dwBytesRecorded + 18 + 20;
	WriteFile(FileHandle, &dwNumber, 4, &NumToWrite, NULL);

	dwNumber = FCC("WAVE");
	WriteFile(FileHandle, &dwNumber, 4, &NumToWrite, NULL);

	dwNumber = FCC("fmt ");
	WriteFile(FileHandle, &dwNumber, 4, &NumToWrite, NULL);

	dwNumber = 18L;
	WriteFile(FileHandle, &dwNumber, 4, &NumToWrite, NULL);

	WriteFile(FileHandle, wf, sizeof(WAVEFORMATEX), &NumToWrite, NULL);

	dwNumber = FCC("data");
	WriteFile(FileHandle, &dwNumber, 4, &NumToWrite, NULL);

	dwNumber = waveHeader->dwBytesRecorded;
	WriteFile(FileHandle, &dwNumber, 4, &NumToWrite, NULL);

	WriteFile(FileHandle, waveHeader->lpData, waveHeader->dwBytesRecorded, &NumToWrite, NULL);
	SetEndOfFile( FileHandle );
	CloseHandle( FileHandle );
	FileHandle = INVALID_HANDLE_VALUE;
	
	_debug_print("SaveRecordtoFile SUCCEED!",1);

	return 0;
}
Пример #12
0
void ADIOI_NTFS_Resize(ADIO_File fd, ADIO_Offset size, int *error_code)
{
    LONG dwTemp;
    DWORD err;
    BOOL result;
    static char myname[] = "ADIOI_NTFS_Resize";

    dwTemp = DWORDHIGH(size);
    err = SetFilePointer(fd->fd_sys, DWORDLOW(size), &dwTemp, FILE_BEGIN);
    /* --BEGIN ERROR HANDLING-- */
    if (err == INVALID_SET_FILE_POINTER)
    {
	err = GetLastError();
	if (err != NO_ERROR)
	{
        char errMsg[ADIOI_NTFS_ERR_MSG_MAX];
        ADIOI_NTFS_Strerror(err, errMsg, ADIOI_NTFS_ERR_MSG_MAX);
	    *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
					   myname, __LINE__, MPI_ERR_IO,
					   "**io",
					   "**io %s", errMsg);
	    return;
	}
    }
    /*printf("setting file length to %d\n", size);fflush(stdout);*/
    /* --END ERROR HANDLING-- */
    result = SetEndOfFile(fd->fd_sys);
    /* --BEGIN ERROR HANDLING-- */
    if (result == FALSE)
    {
    char errMsg[ADIOI_NTFS_ERR_MSG_MAX];
	err = GetLastError();
    ADIOI_NTFS_Strerror(err, errMsg, ADIOI_NTFS_ERR_MSG_MAX);
	*error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
					   myname, __LINE__, MPI_ERR_IO,
					   "**io",
					   "**io %s", errMsg);
	return;
    }
    /* --END ERROR HANDLING-- */
    *error_code = MPI_SUCCESS;
}
Пример #13
0
uint32_t CMappedMemory::_SetSize(uint32_t Size)
{
	if (m_Base)
	{
		myFlushViewOfFile(m_Base, 0);
		myUnmapViewOfFile(m_Base);
	}
	if (m_FileMapping)
		CloseHandle(m_FileMapping);

	m_Base = NULL;
	m_FileMapping = NULL;

	if (INVALID_SET_FILE_POINTER == SetFilePointer(m_DirectFile, Size, NULL, FILE_BEGIN))
	{
		LOGSYS(logERROR, _T("SetFilePointer failed"));
		return 0;
	}

	if (!SetEndOfFile(m_DirectFile))
	{
		LOGSYS(logERROR, _T("Cannot set end of file"));
		return 0;
	}

	m_FileMapping = myCreateFileMappingA(m_DirectFile, NULL, PAGE_READWRITE, 0, Size, NULL);

	if (!m_FileMapping)
	{
		LOGSYS(logERROR, _T("CreateFileMapping failed"));
		return 0;
	}

	m_Base = (uint8_t*) myMapViewOfFile(m_FileMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);
	if (!m_Base)
	{
		LOGSYS(logERROR, _T("MapViewOfFile failed"));
		return 0;
	}

	return Size;
}
Пример #14
0
// ---- C.unistd ---- 
int ftruncate(int fildes, off_t length)
{
    HANDLE hfile;
    unsigned int curpos;

    if( fildes < 0 )
    {
        errno = EBADF;
        return -1;
    }

    if( length < 0 )
    {
        errno = EINVAL;
        return -1;
    }

    hfile = (HANDLE) _get_osfhandle (fildes);
    curpos = SetFilePointer( hfile, 0, NULL, FILE_CURRENT );

    if( (curpos == ~0) ||
        (SetFilePointer( hfile, length, NULL, FILE_BEGIN ) == ~0) ||
        (!SetEndOfFile( hfile )) )
    {
        int error = GetLastError();

        switch( error )
        {
            case ERROR_INVALID_HANDLE:
            errno = EBADF;
            break;

            default:
            errno = EIO;
            break;
        }

        return -1;
    }

    return 0;
}
Пример #15
0
bool vmsSecurity::ExtractFileFromSignedFile(LPCTSTR ptszSrcFile, LPCTSTR ptszDstFile)
{
	HANDLE h = CreateFile (ptszSrcFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (h == INVALID_HANDLE_VALUE)
		return false;
	DWORD dwFileSize = GetFileSize (h, NULL);
	DWORD dwDataSize = dwFileSize > 5000 ? 5000 : dwFileSize;
	if (dwDataSize < strlen (FdmCryptSignatureMarker))
	{
		CloseHandle (h);
		return false;
	}
	LPBYTE pbData = new BYTE [dwDataSize];
	DWORD dw;
	SetFilePointer (h, dwFileSize - dwDataSize, NULL, FILE_BEGIN);
	ReadFile (h, pbData, dwDataSize, &dw, NULL);
	CloseHandle (h);
	
	int nSigLen = strlen (FdmCryptSignatureMarker);
	LPBYTE pbSig = pbData + dwDataSize - nSigLen;
	while (pbSig != pbData && strncmp ((char*)pbSig, FdmCryptSignatureMarker, nSigLen) != 0)
		pbSig--;
	delete [] pbData;
	if (pbData == pbSig)
		return false;

	UINT nSignatureSize = dwDataSize - (pbSig - pbData);

	if (FALSE == CopyFile (ptszSrcFile, ptszDstFile, FALSE))
		return false;

	h = CreateFile (ptszDstFile, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (h == INVALID_HANDLE_VALUE)
		return false;

	SetFilePointer (h, -(int)nSignatureSize, NULL, FILE_END);
	SetEndOfFile (h);

	CloseHandle (h);

	return true;
}
Пример #16
0
static NTSTATUS DOKAN_CALLBACK
MirrorSetAllocationSize(
	LPCWSTR				FileName,
	LONGLONG			AllocSize,
	PDOKAN_FILE_INFO	DokanFileInfo)
{
	WCHAR			filePath[MAX_PATH];
	HANDLE			handle;
	LARGE_INTEGER	fileSize;

	GetFilePath(filePath, MAX_PATH, FileName);

	DbgPrint(L"SetAllocationSize %s, %I64d\n", filePath, AllocSize);

	handle = (HANDLE)DokanFileInfo->Context;
	if (!handle || handle == INVALID_HANDLE_VALUE) {
		DbgPrint(L"\tinvalid handle\n\n");
		return STATUS_INVALID_HANDLE;
	}

	if (GetFileSizeEx(handle, &fileSize)) {
		if (AllocSize < fileSize.QuadPart) {
			fileSize.QuadPart = AllocSize;
			if (!SetFilePointerEx(handle, fileSize, NULL, FILE_BEGIN)) {
				DWORD error = GetLastError();
				DbgPrint(L"\tSetAllocationSize: SetFilePointer eror: %d, "
					L"offset = %I64d\n\n", error, AllocSize);
				return ToNtStatus(error);
			}
			if (!SetEndOfFile(handle)) {
				DWORD error = GetLastError();
				DbgPrint(L"\tSetEndOfFile error code = %d\n\n", error);
				return ToNtStatus(error);
			}
		}
	} else {
		DWORD error = GetLastError();
		DbgPrint(L"\terror code = %d\n\n", error);
		return ToNtStatus(error);
	}
	return STATUS_SUCCESS;
}
Пример #17
0
bool fs::file::trunc(u64 size) const
{
#ifdef _WIN32
	LARGE_INTEGER old, pos;

	pos.QuadPart = 0;
	SetFilePointerEx((HANDLE)m_fd, pos, &old, FILE_CURRENT); // get old position

	pos.QuadPart = size;
	SetFilePointerEx((HANDLE)m_fd, pos, NULL, FILE_BEGIN); // set new position

	SetEndOfFile((HANDLE)m_fd); // change file size

	SetFilePointerEx((HANDLE)m_fd, old, NULL, FILE_BEGIN); // restore position

	return true; // TODO
#else
	return !::ftruncate(m_fd, size);
#endif
}
/**
 *	Truncates an existing file, discarding data at the end to make it smaller. (Thread-safe)
 *
 *	@param Filename		Full path to the file.
 *	@param FileSize		New file size to truncate to. If this is larger than current file size, the function won't do anything.
 *	@return				Resulting file size or INDEX_NONE if the file didn't exist.
 **/
INT FFileManagerWindows::InternalFileTruncate( const TCHAR* Filename, INT FileSize )
{
	INT NewFileSize = INDEX_NONE;
	HANDLE WinHandle = CreateFile( Filename, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
	UBOOL bSuccess = (WinHandle != INVALID_HANDLE_VALUE);
	if ( bSuccess )
	{
		DWORD CurrentFileSize = GetFileSize( WinHandle, NULL );
		NewFileSize = INT(CurrentFileSize);
		UBOOL bSuccess = (CurrentFileSize != INVALID_FILE_SIZE);
		if ( bSuccess && CurrentFileSize > DWORD(FileSize) )
		{
			DWORD NewPosition = SetFilePointer( WinHandle, FileSize, NULL, FILE_BEGIN );
			bSuccess = bSuccess && NewPosition == DWORD(FileSize) && SetEndOfFile( WinHandle );
			NewFileSize = FileSize;
		}
		CloseHandle( WinHandle );
	}
	return bSuccess ? NewFileSize : INDEX_NONE;
}
Пример #19
0
void f_local_fwriter::set_file_size (uint64_t filsize)
{
	open_file ();
#ifdef _WIN32
	uint64_t offset = this->seek_file (filsize, FILE_BEGIN);
	if (offset != filsize) {
		std::string errmsg = fmt_string ("Can't seek file %s(%s)."
			, f_name_.c_str (), error_msg ().c_str ());
		THROW_XDELTA_EXCEPTION (errmsg);
	}
	BOOL success = SetEndOfFile (f_handle_);
#else
	int success = ftruncate (f_fd_, filsize);
	success = success == 0 ? 1 : 0;
#endif
	if (!success) {
		std::string errmsg = fmt_string ("Can't set file  %s's size.", f_name_.c_str ());
		THROW_XDELTA_EXCEPTION (errmsg);
	}	
}
Пример #20
0
/******************************************************************************
 *      ILockBytes_SetSize
 *
 * Sets the size of the file.
 *
 */
static HRESULT WINAPI FileLockBytesImpl_SetSize(ILockBytes* iface, ULARGE_INTEGER newSize)
{
    FileLockBytesImpl* This = impl_from_ILockBytes(iface);
    HRESULT hr = S_OK;
    LARGE_INTEGER newpos;

    if (This->filesize.u.LowPart == newSize.u.LowPart)
        return hr;

    TRACE("from %u to %u\n", This->filesize.u.LowPart, newSize.u.LowPart);

    newpos.QuadPart = newSize.QuadPart;
    if (SetFilePointerEx(This->hfile, newpos, NULL, FILE_BEGIN))
    {
        SetEndOfFile(This->hfile);
    }

    This->filesize = newSize;
    return hr;
}
Пример #21
0
int gmx_truncatefile(char *path, gmx_off_t length)
{
#ifdef _MSC_VER
    /* Microsoft visual studio does not have "truncate" */
    HANDLE fh;
    LARGE_INTEGER win_length;

    win_length.QuadPart = length;

    fh = CreateFile(path,GENERIC_READ | GENERIC_WRITE,0,NULL,
            OPEN_EXISTING,0,NULL);
    SetFilePointerEx(fh,win_length,NULL,FILE_BEGIN);
    SetEndOfFile(fh);
    CloseHandle(fh);

    return 0;
#else
    return truncate(path,length);
#endif
}
Пример #22
0
//
// CloseFile
//
HRESULT FileWriter::CloseFile()
{
	if (m_hFile == INVALID_HANDLE_VALUE)
	{
		return S_OK;
	}

	if (m_bChunkReserve)
	{
		__int64 currentPosition = GetFilePointer();
		SetFilePointer(currentPosition, FILE_BEGIN);
		SetEndOfFile(m_hFile);
	}

	CloseHandle(m_hFile);
	m_hFile = INVALID_HANDLE_VALUE; // Invalidate the file

	return S_OK;

}
Пример #23
0
/* We write our own ftruncate because the one in the
   Microsoft library mrcrt.dll does not truncate
   files greater than 2GB.
   KES - May 2007 */
int win32_ftruncate(int fd, int64_t length) 
{
	// Set point we want to truncate file.
	__int64 pos=_lseeki64(fd, (__int64)length, SEEK_SET);

	if(pos!=(__int64)length)
	{
		errno=EACCES;
		return -1;
	}

	// Truncate file.
	if(!SetEndOfFile((HANDLE)_get_osfhandle(fd)))
	{
		errno=b_errno_win32;
		return -1;
	}
	errno=0;
	return 0;
}
Пример #24
0
BOOL WINAPI ExtractEFSFile(
	IN EFSHANDLEFORREAD hEFSFile,
	IN DWORD dwComponentID,
	IN DWORD dwFileID,
	IN LPCSTR lpszFileName
)
{
	assert(lpszFileName);

	// This is exactly the same procedure for ExtractResource
	// Find the file in the EFS archive (if it exists)
	LPCVOID lpvFileData;
	DWORD dwFileSize;
	if (!LookupEFSFile(hEFSFile, dwComponentID, dwFileID, &lpvFileData, &dwFileSize, NULL))
		return FALSE;

	// Open the output file
	HANDLE hOutFile = CreateFile(lpszFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
	if (hOutFile == INVALID_HANDLE_VALUE)
		return FALSE;

	BOOL bRetVal = FALSE;

	// Write the file in one shot, as it's all mapped into memory
	DWORD dwBytesRead;
	if (WriteFile(hOutFile, lpvFileData, dwFileSize, &dwBytesRead, NULL)
		&& (dwBytesRead == dwFileSize))
	{
		SetEndOfFile(hOutFile);

		bRetVal = TRUE;
	}

	CloseHandle(hOutFile);

	// Delete the file if extraction failed
	if (!bRetVal)
		DeleteFile(lpszFileName);

	return bRetVal;
}
/***********************************************
Close
	Close data file
PARAM:
	none
RETURN:
	-1 if error
************************************************/
int	CUT_MapFileDataSource::Close() {
	int		rt = UTE_SUCCESS;

	m_lnSize = m_lnActualSize;

	// Flush file 
	if(m_lpMapAddress != NULL) 
		if(!FlushViewOfFile(m_lpMapAddress, 0))
			rt = -1;

	// Unmap
	if(m_lpMapAddress != NULL) {
		if(!UnmapViewOfFile(m_lpMapAddress))
			rt = -1;
		m_lpMapAddress = NULL;
		}

	// Close file mapping
	if(m_hMapFile != NULL) {
		if(!CloseHandle(m_hMapFile))
			rt = -1;
		m_hMapFile = NULL;
		}


	// Close file
	if(m_hFile != INVALID_HANDLE_VALUE) {
		// Set Actual file size
		if(SetFilePointer(m_hFile, m_lnActualSize.LowPart, (long *)&m_lnActualSize.HighPart, FILE_BEGIN ) == 0xFFFFFFFF && GetLastError() != NO_ERROR)
			return -1;
		if(!SetEndOfFile(m_hFile))
			return -1;

		// Close file
		if(!CloseHandle(m_hFile))
			rt = -1;
		m_hFile = INVALID_HANDLE_VALUE;
		}	

	return rt;
}
Пример #26
0
//database functions
void dbsave()
{
    dprintf("Saving database...");
    DWORD ticks = GetTickCount();
    JSON root = json_object();
    CommentCacheSave(root);
    LabelCacheSave(root);
    BookmarkCacheSave(root);
    FunctionCacheSave(root);
    LoopCacheSave(root);
    BpCacheSave(root);
    WString wdbpath = StringUtils::Utf8ToUtf16(dbpath);
    if(json_object_size(root))
    {
        Handle hFile = CreateFileW(wdbpath.c_str(), GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
        if(!hFile)
        {
            dputs("\nFailed to open database for writing!");
            json_decref(root); //free root
            return;
        }
        SetEndOfFile(hFile);
        char* jsonText = json_dumps(root, JSON_INDENT(4));
        DWORD written = 0;
        if(!WriteFile(hFile, jsonText, (DWORD)strlen(jsonText), &written, 0))
        {
            json_free(jsonText);
            dputs("\nFailed to write database file!");
            json_decref(root); //free root
            return;
        }
        hFile.Close();
        json_free(jsonText);
        if(!settingboolget("Engine", "DisableDatabaseCompression"))
            LZ4_compress_fileW(wdbpath.c_str(), wdbpath.c_str());
    }
    else //remove database when nothing is in there
        DeleteFileW(wdbpath.c_str());
    dprintf("%ums\n", GetTickCount() - ticks);
    json_decref(root); //free root
}
/*
	BSD systems provide ftruncate, several others supply chsize, and a few
	may provide a (possibly undocumented) fcntl option F_FREESP. Under MS-DOS,
	you can sometimes use write(fd, "", 0). However, there is no portable
	solution, nor a way to delete blocks at the beginning.
*/
static void MelderFile_truncate (MelderFile me, long size) {
#if defined(_WIN32)

	HANDLE hFile;
	DWORD fdwAccess = GENERIC_READ | GENERIC_WRITE, fPos;
	DWORD fdwShareMode = 0; /* File cannot be shared */
	LPSECURITY_ATTRIBUTES lpsa = NULL;
	DWORD fdwCreate = OPEN_EXISTING;
	LARGE_INTEGER fileSize;

	MelderFile_close (me);

	hFile = CreateFileW (my path, fdwAccess, fdwShareMode, lpsa, fdwCreate,
	                     FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile == INVALID_HANDLE_VALUE) {
		Melder_throw ("Can't open file ", MelderFile_messageName (me), ".");
	}

	// Set current file pointer to position 'size'

	fileSize.LowPart = size;
	fileSize.HighPart = 0; /* Limit the file size to 2^32 - 2 bytes */
	fPos = SetFilePointer (hFile, fileSize.LowPart, &fileSize.HighPart, FILE_BEGIN);
	if (fPos == 0xFFFFFFFF) {
		Melder_throw ("Can't set the position at size ", size, "for file ", 	MelderFile_messageName (me), ".");
	}

	// Limit the file size as the current position of the file pointer.

	SetEndOfFile (hFile);
	CloseHandle (hFile);

#elif defined(linux) || defined(macintosh)

	MelderFile_close (me);
	if (truncate (Melder_peekWcsToUtf8 (my path), size) == -1) Melder_throw ("Truncating failed for file ",
		        MelderFile_messageName (me), " (", Melder_peekUtf8ToWcs (strerror (errno)), ").");
#else
	Melder_throw ("Don't know what to do.");
#endif
}
Пример #28
-1
	bool Resize(const AnyString& filename, uint64_t size)
	{
		if (not filename.empty())
		{
			if (size < std::numeric_limits<off_t>::max())
			{
				#ifndef YUNI_OS_WINDOWS
				{
					assert((filename.c_str())[filename.size()] == '\0');
					#ifdef YUNI_OS_MAC
					int fd = open(filename.c_str(), O_WRONLY|O_CREAT, 0644);
					#else
					int fd = open(filename.c_str(), O_WRONLY|O_CREAT|O_LARGEFILE, 0644);
					#endif
					if (fd != -1)
					{
						bool success = (0 == ftruncate(fd, static_cast<off_t>(size)));
						close(fd);
						return success;
					}
				}
				#else
				{
					WString wstr(filename, true);
					if (not wstr.empty())
					{
						HANDLE hndl = CreateFileW(wstr.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
						if (hndl)
						{
							LARGE_INTEGER li;
							li.QuadPart = size;
							DWORD dwPtr = SetFilePointer(hndl, li.LowPart, &li.HighPart, FILE_BEGIN);
							if (dwPtr != INVALID_SET_FILE_POINTER)
								SetEndOfFile(hndl);
							CloseHandle(hndl);
							return true;
						}
					}
				}
				#endif
			}
		}
		return false;
	}
Пример #29
-1
int
WIN32_ftruncate(int fd, off_t size)
{
    HANDLE file;
    DWORD error;
    LARGE_INTEGER size64;
    LARGE_INTEGER test64;

    if (fd < 0) {
	errno = EBADF;
	return -1;
    }
    size64.QuadPart = (__int64) size;
    test64.QuadPart = 0;

    file = (HANDLE) _get_osfhandle(fd);

    /* Get current file position to check File Handle */
    test64.LowPart = SetFilePointer(file, test64.LowPart, &test64.HighPart, FILE_CURRENT);
    if ((test64.LowPart == INVALID_SET_FILE_POINTER) && ((error = GetLastError()) != NO_ERROR))
	goto WIN32_ftruncate_error;

    /* Set the current File Pointer position */
    size64.LowPart = SetFilePointer(file, size64.LowPart, &size64.HighPart, FILE_BEGIN);
    if ((size64.LowPart == INVALID_SET_FILE_POINTER) && ((error = GetLastError()) != NO_ERROR))
	goto WIN32_ftruncate_error;
    else if (!SetEndOfFile(file)) {
	int error = GetLastError();
	goto WIN32_ftruncate_error;
    }
    return 0;

  WIN32_ftruncate_error:
    switch (error) {
    case ERROR_INVALID_HANDLE:
	errno = EBADF;
	break;
    default:
	errno = EIO;
	break;
    }

    return -1;
}
Пример #30
-1
/*
 * __win_file_set_end --
 *	Truncate or extend a file.
 */
static int
__win_file_set_end(
    WT_FILE_HANDLE *file_handle, WT_SESSION *wt_session, wt_off_t len)
{
	DWORD windows_error;
	LARGE_INTEGER largeint;
	WT_DECL_RET;
	WT_FILE_HANDLE_WIN *win_fh;
	WT_SESSION_IMPL *session;

	win_fh = (WT_FILE_HANDLE_WIN *)file_handle;
	session = (WT_SESSION_IMPL *)wt_session;

	largeint.QuadPart = len;

	if (win_fh->filehandle_secondary == INVALID_HANDLE_VALUE)
		WT_RET_MSG(session, EINVAL,
		    "%s: handle-set-end: no secondary handle",
		    file_handle->name);

	if (SetFilePointerEx(win_fh->filehandle_secondary,
	    largeint, NULL, FILE_BEGIN) == FALSE) {
		windows_error = __wt_getlasterror();
		ret = __wt_map_windows_error(windows_error);
		__wt_err(session, ret,
		    "%s: handle-set-end: SetFilePointerEx: %s",
		    file_handle->name,
		    __wt_formatmessage(session, windows_error));
		return (ret);
	}

	if (SetEndOfFile(win_fh->filehandle_secondary) == FALSE) {
		if (GetLastError() == ERROR_USER_MAPPED_FILE)
			return (__wt_set_return(session, EBUSY));
		windows_error = __wt_getlasterror();
		ret = __wt_map_windows_error(windows_error);
		__wt_err(session, ret,
		    "%s: handle-set-end: SetEndOfFile: %s",
		    file_handle->name,
		    __wt_formatmessage(session, windows_error));
		return (ret);
	}
	return (0);
}