PDA

View Full Version : [c] ReadTextFile() Unicode <-> Ansi


darkone
11-27-2003, 09:10 AM
BOOL ReadTextFile(LPTSTR tszFileName, TCHAR **lpTextBuffer, LPDWORD lpTextBufferSize)
{
HANDLE hFile;
DWORD dwFileSize, dwError, dwBytesRead;
TCHAR *lpBuffer;

dwError = NO_ERROR;
// Open file
hFile = CreateFile(tszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE) return FALSE;
if ((dwFileSize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE)
{
dwError = GetLastError();
CloseHandle(hFile);
ERROR_RETURN(dwError, FALSE);
}

// Buffer file to memory
lpBuffer = (TCHAR *)Allocate("ReadBuffer", dwFileSize + sizeof(TCHAR));
if (! lpBuffer)
{
CloseHandle(hFile);
ERROR_RETURN(ERROR_NOT_ENOUGH_MEMORY, FALSE);
}
if (! ReadFile(hFile, lpBuffer, dwFileSize, &dwBytesRead, NULL))
{
dwError = GetLastError();
CloseHandle(hFile);
Free(lpBuffer);
ERROR_RETURN(dwError, FALSE);
}
if (dwBytesRead < sizeof(TCHAR))
{
CloseHandle(hFile);
Free(lpBuffer);
lpTextBuffer = NULL;
lpTextBufferSize = 0;
return TRUE;
}


// Convert buffer to tchar
#ifdef _UNICODE
if (((WCHAR *)lpBuffer)[0] != 65279)
{
// Buffer is not unicode encoded
lpTextBuffer[0] = (WCHAR *)Allocate("ReadBuffer", (dwBytesRead + 1) * sizeof(WCHAR));
if (lpTextBuffer[0])
{
lpTextBufferSize[0] = swprintf(lpTextBuffer[0], ((PCHAR)lpBuffer)[dwBytesRead - 1] == '\n' ? L"%.*S" : L"%.*S\n", dwBytesRead, lpBuffer);
}
else dwError = ERROR_NOT_ENOUGH_MEMORY;
}
else
{
// Buffer is unicode encoded
dwBytesRead = (dwBytesRead & (0xFFFFFFFF - (sizeof(WCHAR) - 1))) / sizeof(WCHAR);

MoveMemory(lpBuffer, &lpBuffer[1], (--dwBytesRead) * sizeof(WCHAR));
if (lpBuffer[dwBytesRead - 1] != L'\n') lpBuffer[dwBytesRead++] = L'\n';
lpTextBuffer[0] = lpBuffer;
lpTextBufferSize[0] = dwBytesRead;
lpBuffer = NULL;
}
#else
if (((WCHAR *)lpBuffer)[0] == 65279)
{
// Buffer is unicode encoded
dwBytesRead = (dwBytesRead & (0xFFFFFFFF - (sizeof(WCHAR) - 1))) / sizeof(WCHAR);
lpTextBuffer[0] = (PCHAR)Allocate("ReadBuffer", dwBytesRead + 1);
if (lpTextBuffer[0])
{
lpTextBufferSize[0] = sprintf(lpTextBuffer[0], ((WCHAR *)lpBuffer)[dwBytesRead - 1] == L'\n' ? "%.*S" : "%.*S\n", dwBytesRead - 1, lpBuffer + sizeof(WCHAR));
}
else dwError = ERROR_NOT_ENOUGH_MEMORY;
}
else
{
// Buffer is not unicode encoded
if (lpBuffer[dwBytesRead - 1] == '\n') lpBuffer[dwBytesRead++] = '\n';
lpTextBuffer[0] = lpBuffer;
lpTextBufferSize[0] = dwBytesRead;
lpBuffer = NULL;
}
#endif
CloseHandle(hFile);
Free(lpBuffer);
if (dwError) ERROR_RETURN(dwError, FALSE);
return TRUE;
}