读写Unicode带中文的txt文件

这是一个C++程序,用于读取包含Unicode编码的TXT文件,并处理其中的中文字符。程序首先读取文件,跳过Unicode文件头,然后通过查找等号将文本拆分为两部分,并进行修剪操作。接着,它识别并提取中文字符,最后将处理后的数据保存到新的Unicode文本文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// readtxt.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include<fstream>
#include <iostream>
#include <vector>


std::vector<tstring> m_vSave;

using namespace std;

tstring getline(FILE *stream)
{
 tstring strRet;
 TCHAR line[100] = {0};
 while( _fgetts( line, 100, stream ) != NULL)
 {
  if (line[0] == 0xFEFF) //unicode 文件的头
  {
   strRet += &line[1];
  }
  else
  {
   strRet += line;
  }
  if (line[_tcslen(line)-1] == _T('\n'))
  {
   break;
  }
 }
 return strRet;
}

void Trim( tstring& str , const tstring& chars =_T(" \t" ))
{
 str.erase(str.find_last_not_of(chars)+1);
 str.erase(0, str.find_first_not_of(chars));
}

int main(int argc,char **argv)
{
 FILE *stream = NULL;
 FILE *streamOut = NULL;
 if( _wfopen_s( &stream,_T("E:\\1.txt"), _T("rt+,ccs=UNICODE ") ) == 0 )
 {
  tstring sRead;
  while (!feof(stream))
  {
   sRead = getline(stream);
   if (sRead.empty())
   {
    continue;
   }
   else
   {
    int n;
    n=sRead.find(_T("="));
    tstring s1 = _T("");
    tstring s2 = _T("");
    s1=sRead.substr(0,n);
    s2=sRead.substr(n+1,sRead.length()); 
    Trim(s1);
    Trim(s2);
    TCHAR tstrInitial[200]={0};
    TCHAR tstrChinese[200]={0};
    TCHAR tstrEspecial[200]={0};
    bool flag = false;
    _tcscpy(tstrInitial ,s2.c_str());
    int j =0;

    for(int i=0; i<s2.length(); i++)
    {

     if ((tstrInitial[i]>=0x4E00)&&(tstrInitial[i]<=0x9FA5))
     {
      tstrChinese[j] = tstrInitial[i] ;
      /*tstrChinese[++j] = tstrInitial[++i];*/
      j++;
      flag = true;
     }
     else
     {
      if (flag==true)
      {
       break;
      }
      else
      {
       ;
      }     
     }

    }

    tstrChinese;
    tstring data =_T("");
    data+= s1;
    data+=_T("=");
    data+=tstrChinese;
    data+=_T("\n");
    m_vSave.push_back(data);
   }    
  }
 }
 if( _wfopen_s( &streamOut,_T("E:\\2.txt"), _T("wt,ccs=UNICODE ") ) == 0 )
 {
  for(int k=0;k<m_vSave.size();k++)
  {
   fputws(m_vSave[k].c_str(),streamOut);
  } 
 }
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值