1. 程式人生 > >ofstream開啟中文路徑的三種方法

ofstream開啟中文路徑的三種方法

 經測試第一種方法在VS2008環境下無效

 1: /********************************************************************

   2:     created:    2008/05/10
   3:     created:    10:5:2008   23:56
   4:     filename:     k:/sj/fstreamTest/fstreamTest/main.cpp
   5:     file path:    k:/sj/fstreamTest/fstreamTest
   6:     file base:    main
   7:     file ext:    cpp
   8:     author:        Gohan
   9: *********************************************************************/
  10: #include <tchar.h>
  11: #include <fstream>
  12: #include <iostream>
  13: using namespace std;
  14: int main()
  15: {
  16:     /************************************************************************/
  17:     /* 方法1,使用_TEXT()巨集定義將字串常量指定為TCHAR*型別                 */
  18:     /* 如果是我,首選此型別                                                 */
  19:     /************************************************************************/
  20:     fstream file;
  21:     file.open(_TEXT("c://測試//測試文字.txt"));
  22:     cout<<file.rdbuf();
  23:     file.close();
  24:  
  25:     /************************************************************************/
  26:     /* 方法2,使用STL中的locale類的靜態方法指定全域性locale                   */
  27:     /* 使用該方法以後,cout可能不能正常輸出中文,十分蹊蹺                    */
  28:     /* 我發現了勉強解決的方法:不要在還原區域設定前用cout或wcout 輸出中文   */
  29:     /* 否則後果就是還原區域設定後無法使用cout wcout輸出中文                 */
  30:     /************************************************************************/
  31:     locale::global(locale(""));//將全域性區域設為作業系統預設區域
  32:     file.open("c://測試//測試文字2.txt");//可以順利開啟檔案了
  33:     locale::global(locale("C"));//還原全域性區域設定
  34:     cout<<file.rdbuf();
  35:     file.close();
  36:  
  37:     /************************************************************************/
  38:     /* 方法3,使用C函式setlocale,不能用cout輸出中文的問題解決方法同上      */
  39:     /************************************************************************/
  40:     setlocale(LC_ALL,"Chinese-simplified");//設定中文環境
  41:     file.open("c://測試//測試文字3.txt");//可以順利開啟檔案了
  42:     setlocale(LC_ALL,"C");//還原
  43:     cout<<file.rdbuf();
  44:     file.close();