我正在尝试编写一个读写文件的类。对于字符串,有两种方法:ANSI 和 Unicode。ANSI 函数没问题,但我的 Unicode 函数有问题。
有点连线,我可以直接读取 Unicode 文件,而无需检查或跳过“0xFEFF”内容。无论我使用哪种语言(我尝试过英语、中文和日语),它都可以正常工作。有什么我应该知道的吗?
然后最大的问题就跳出来了:将Unicode字符串写入文件。首先我尝试了简单的英语作为没有'\n'字符的字母,它确实很好用。然后我将 '\n' 推入并开始出现问题:输出插入了许多空格,如“abcdefg \nhijklmn \nopqrst \nuvwxyz”('\n' 有效,但有很多空格)并且文件再次为 ANSI。不要问其他语言的字符,我什至根本看不懂。
所以这里有一个问题:我应该怎么做才能正确地将Unicode字符串写入文件以及如何?请不要提及“_wopen”功能,文件已经用“fopen”功能打开。
答案和建议将不胜感激。
我正在使用 Windows 7 和 Visual Studio。
编辑:它适用于具有以下代码的非英文字符,但 '\n' 仍然错误。
char* cStart = "\xff\xfe";
if (::ftell(m_pFile) == 0)
::fwrite(cStart, sizeof(wchar_t), 1, m_pFile);
但这是如何工作的?我的意思是我在阅读文件时没有看到它。
编辑:我的代码的一部分。
void File::ReadWText(wchar_t* pString, uint32 uLength)
{
wchar_t cLetter = L'\0';
uint32 uIndex = 0;
do {
cLetter = L'\0';
::fread(&cLetter, sizeof(wchar_t), 1, m_pFile);
pString[uIndex] = cLetter;
}while (cLetter != L'\0' && !::feof(m_pFile) && uIndex++ < uLength);
pString[uIndex] = L'\0';
}
void File::WriteWText(wchar_t* pString, uint32 uLength)
{
char* pStart = "\xff\xfe";
if (::ftell(m_pFile) == 0)
::fwrite(pStart, sizeof(wchar_t), 1, m_pFile);
m_uSize += sizeof(wchar_t) * ::fwrite(pString, sizeof(wchar_t), uLength, m_pFile);
}
void main()
{
::File* pFile = new File();
wchar_t* pWString = L"abcdefg\nhijklmn\nopqrst\nuvwxyz";
pFile->Open("TextW.txt", File::Output);
// fopen("TextW.txt", "w");
pFile->WriteWText(pWString, ::wcslen(pWString));
pFile->Close();
}
输出文件内容为:“abcdefg栀碗樀欀氀洀渀ഀopqrst甀淤眀砀礀稀”,文件为Unicode。
我不知道它是否是“L'\n'”的正确表达,我以前从未使用过Unicode。谢谢你帮助我:)