
/*	Copyright (C) G. Jespersen
	See Licence.txt.*/

//
// From: https://www.codeproject.com/Articles/4119/CStdioFile-derived-class-
//			for-multibyte-and-Unicode

// StdioFileEx.h: interface for the CStdioFileEx class.
//
// Version 1.1 23 August 2003.	 Incorporated fixes from Dennis Jeryd.
// Version 1.3 19 February 2005. Incorporated fixes from Howard J Oh and some of my own.
// Version 1.4 26 February 2005. Fixed stupid screw-up in code from 1.3.
// Version 1.5 18 November 2005. Incorporated fixes from Andy Goodwin.
//								 Allows code page to be specified for reading/writing.
//								 Properly calculates multibyte buffer size instead of
//								   assuming lstrlen(s).
//								 Should handle UTF8 properly.
//
// Copyright David Pritchard 2003-2005. davidpritchard@ctv.es
//

#if !defined(AFX_STDIOFILEEX_H__41AFE3CA_25E0_482F_8B00_C40775BCDB81__INCLUDED_)
#define AFX_STDIOFILEEX_H__41AFE3CA_25E0_482F_8B00_C40775BCDB81__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#define	UNICODE_BOM					0xFEFF		// Unicode "byte order mark" which goes at start of file
#define	NEWLINE						_T("\r\n")	// New line characters
#define	DEFAULT_UNICODE_FILLER_CHAR	"#"			// Filler char used when no conversion from Unicode to local code page is possible

class CStdioFileEx: public CStdioFile
{
public:
	CStdioFileEx();
	CStdioFileEx(LPCTSTR lpszFileName, UINT nOpenFlags);

	virtual BOOL	Open(LPCTSTR lpszFileName, UINT nOpenFlags, CFileException * pError = NULL);
	virtual BOOL	ReadString(CString& rString);
	virtual void	WriteString( LPCTSTR lpsz );
	bool			IsFileUnicodeText()	{ return m_bIsUnicodeText; }	
	unsigned long	GetCharCount();


	void SetCodePage(const UINT nCodePage);

	// Gets a Unicode string from a MultiByte string.
	static int GetUnicodeStringFromMultiByteString(LPCSTR szMultiByteString, 
												   wchar_t* szUnicodeString, 
												   int nUnicodeBufferSize, 
												   int nCodePage = -1);
	// Gets a MultiByte string from a Unicode string.
	static int GetMultiByteStringFromUnicodeString(wchar_t * szUnicodeString,
												   char * szMultiByteString,
												   int nMultiByteBufferSize,
												   int nCodePage = -1);

	// Obtains the multi-byte buffer size needed to accommodate a converted Unicode string.
	static int GetRequiredMultiByteLengthForUnicodeString(wchar_t * szUnicodeString,
														  int nCodePage = -1);

	// Determines whether a file is Unicode by reading the first character 
	// and detecting whether it's the Unicode byte marker.
	static bool IsFileUnicode(const CString & sFilePath);

	static UINT	GetCurrentLocaleCodePage();

protected:
	UINT ProcessFlags(const CString & sFilePath, UINT & nOpenFlags);

	// Attributes
	//
public:
	// Additional flag to allow Unicode text writing
	static const UINT modeWriteUnicode;

protected:
	bool m_bIsUnicodeText;
	UINT m_nFlags;
	int	 m_nFileCodePage;
};

#endif // !defined(AFX_STDIOFILEEX_H__41AFE3CA_25E0_482F_8B00_C40775BCDB81__INCLUDED_)
