在 Unicode/MBCS 应用程序中,从/向 ANSI/Unicode 编码的文本文件中读取或写入行






3.83/5 (10投票s)
2006年1月18日
2分钟阅读

146520

1785
一篇关于如何从/向 ANSI/Unicode 类型的文本文件中读取/写入行的文章。
引言
在编程中,从或向文本文件中读取或写入一行可能是一项非常常见的任务。CTextFileIO
类旨在简化此任务,无论您的文本文件编码类型如何,以及您的程序环境是 ANSI 还是 Unicode。该类可以正确读取/写入 ANSI、UTF-8、UTF-16 小端、和 UTF-16 大端编码的文本文件。它的目标是在 MBCS 程序或 Unicode 程序中简化从/向 Unicode 或 ANSI 编码的文本文件中读取/写入行。您不必担心文件的编码类型或程序的环境,它会为您完成所有这些工作。该类可以读取或写入由记事本或任何与记事本兼容的编辑器(如 UltraEdit 或 EditPlus)以 ANSI、UTF-8、Unicode 或 Unicode 大端编码创建的文本文件。
背景
当我们编程时,总是需要从或向文本文件中读取或写入一行。过去,这可能是一项非常简单的任务,因为我们只使用 ANSI 编码的文本文件,并且我们的程序环境也是 ANSI 或 MBCS。但是,当我们使用 Unicode 文本文件或在 Unicode 程序中时,它会变得更加困难。因此,我编写了这个类来简化此任务。
使用代码
如果您想在您的程序中使用 CTextFileIO
类,只需将 TextFileIO.h 和 TextFileIO.cpp 添加到您的项目中即可。从文本文件中读取或写入一行非常简单。声明一个 CTextFileIO
对象。然后使用 ReadLine
或 WriteLine
函数。它将自动检测文件的编码类型和您的程序环境。只需使用适当的函数来读取或写入一行即可。
// First, we declare an CTextFileIO object CTextFileIO configFile; // Then, we open the file, notice we should // always open the file in binary mode // If your program is Unicode, use OpenW, otherwise use OpenA configFile.OpenW(L"config.txt",L"rb"); // If you want write to file, should use "wb" or "ab" // For simple, you can just declare an object // and open it in one step like this // CTextFileIO configFile(_T("config.txt"),_T("rb")) // In Unicode application, it's will use OpenW // and in ANSI program, it's use OpenA function // Now we read a line from config file // tstring is std::wstring in Unicode application // and std::string in others tstring aLine; configFile.ReadLine(aLine); // If you want use LPTSTR instead STL string, // do just like following // LPTSTR aLine; // configFile.ReadLine(aLine); // Write a line to file is very like read a line, // just open the file in "write" or "append" mode // Then use WriteLine as ReadLine tstring aLine=_T("a test line"); configFile.WriteLine(aLine); // It will auto append a EOL at the end of line
关注点
在 ANSI (MBCS) 程序中读取 Unicode 文本文件,或在 Unicode 程序中读取 ANSI 文件,这非常令人恼火,我们总是需要担心程序环境和文本文件编码类型。最初,我想使用 CStdioFile
和 CString
对象来完成这项工作,但那没有正确运行。