Unicode文件的读写

【字符编码系列之四】Unicode实现之UTF-8详解 字符 代码点空间 | UTF-8 字节序列 (十六进制表示) | (二进制表示) --------------------+--------------------------------------------- 0000 0000-0000 007F | 0xxxxxxx 0000 0080-0000 07FF | 110xxxxx 10xxxxxx 0000 0800-0000 FFFF | 1110xxxx 10xxx 阅读详情

由于之前没有对Unicode文件的读写写过代码,对其了解甚少,今天搞了一天Unicode文件的读写,现在终于明白了好多问题,跟大家分享一下吧。

          至于Unicode编码的定义我就不说了,自己查资料去吧。

          以Unicode编码的文件开头的两个字节(即第一个字符)是硬性规定的,即0xfeff(还有一种Unicode编码文件的是0xfffe,这里先不介绍),故大家在读文件头的时候可以据此判断该文件是不是Unicode编码的文件.

          当我把文件的内容读到一个WCHAR变量数组的里时,第一个元素就是0xfeff,该文件的实际内容是从第二个元素开始的,这个我开始不知道,弄得我头疼了半天,后来通过调试并监视数据终于知道了。下面给一个我写的有关读取Unicode和ansi编码文件的小程序代码:

void CUnicode文件读写Dlg::OnBnClickedOk()
{
 // 读Unicode编码的文件
 WCHAR FileName[128];
 wcscpy_s(FileName,_countof(FileName),_T(""));
 GetCurrentDirectory(128,FileName);
 wcscat_s(FileName,_countof(FileName),_T("//Data//Unicode.txt")); // 该文件的内容为"Hello 中国,中华人民共和国    Good"

 CFile file(FileName,CFile::modeCreate |
 CFile::modeNoTruncate | CFile::typeBinary |
 CFile::modeReadWrite  | CFile::shareDenyNone);

 WCHAR FileContent[10];
 wcscpy_s(FileContent,_countof(FileContent),_T(""));

 file.Seek(0,CFile::begin);   // 如果只需要文件中的实际内容,可以从第三个字节开始读取,即"file.Seek(2,CFile::begin);",不能为"file.Seek(1,CFile::begin);",否则会出现乱码
 file.Read(FileContent,18);   // 第二个参数为读取18字节(即9个字符,包括了第一个字符0xfeff,实际有用的为后8个字符)

 FileContent[9]='/0';    // 如果文件后方还有其他字符,需要添加结束字符'/0'

 int size=wcslen(FileContent);  // 得到的长度为9个字符,但实际上你能看见的只有8个字符,这里让我郁闷了半天,这里明白了后面就很容易理解了

 WCHAR ch[50];      // 每一个元素为两个字节,即该数组占用了100个字节
 wcscpy_s(ch,_countof(ch),_T("Hello 中国,中华人民共和国"));

 int chLen=wcslen(ch);    // 该值等于16
 int readLen=wcslen(FileContent); // 该值为9

 int ret = wcsncmp(&FileContent[1],ch,readLen-1); // 对前8个字符进行比较,这里需要从第二个元素开始比较

 long asc=(long)FileContent[0];      // 取第一个元素,验证是否为0xfeff,即Unicode编码文件的标志

 if(asc==0xfeff)
 {
  // Do something
  MessageBox(_T("OK!"));       // 程序将出现OK对话框
 }
 else
 {
  // Do something
  MessageBox(_T("No!"));
 }
}

void CUnicode文件读写Dlg::OnBnClickedButton1()
{
 // 读取ANSI编码的文件
 WCHAR FileName[128];
 wcscpy_s(FileName,_countof(FileName),_T(""));
 GetCurrentDirectory(128,FileName);
 wcscat_s(FileName,_countof(FileName),_T("//Data//Ansi.txt"));  // 该文件内容为“Hello 中国,中华人民共和国”

 char FileContent[50]="";

 CFile file(FileName,CFile::modeCreate |
 CFile::modeNoTruncate | CFile::typeBinary |
 CFile::modeReadWrite  | CFile::shareDenyNone);

 file.Seek(0,CFile::begin);
 file.Read(FileContent,16);

 int size=strlen(FileContent);
}

MFC使用CFile读写Unicode字符集文件 阅读详情

相关推荐

VC Unicode工程读写文本文件

因为Windows底层处理字符串是以Unicode形式处理的,所以现在一般使用VC开发软件时都选择Unicode的工程。在Unicode工程中,读写文本文件就会有一个比较纠结的问题:      一般情况下我们新建和编辑的文本文件都是ANSI格式的,而在ANSI工程中用着十分方便的CStdioFile读取字符串时使用的是CString类型, 这就导致Unicode工程环境下CStdioFile将Ansi的字符串读取到了CStringW类型中,即使想使用CA2W来转, 也会出现类型不匹配的错误。      这种

ksksks的专栏 4040

Unicode环境下用CFile对文件操作(解决读写乱码)(运行环境vs2015)

全部都是论坛上找到的代码,自己整理了一下,主要目的是方便以后自己查找使用。 判断文件是Unicode编码还是ANSI编码 int IsUnicodeFile(PTSTR pstrName)//这个函数是判断函数,()内是文件路径,如果是Unicode则该函数值是1 { try { CFile file(pstrName, CFile::modeRead)...

weixin_42792014的博客 2916

交叉编译Qt6.5.3(RK3568开发板)

注意,如果使用其它版本的交叉编译器的话,请确保你的交叉编译器能够支持 C++17标准。为确保后续交叉编译没问题,需要确保开发板使用的GLIBC版本不小于2.34版本。到 linaro 网站上下载交叉编译工具,我下载的是 gcc-linaro-11.3.1-2022.06-x86_64_aarch64-linux-gnu.tar.xz。安装 CMake ,最低要求3.16版本,如果要静态编译,需要3.21及以上版本。我使用的3.27版本。:指定为最后交叉编译后的Qt6.5.3库的安装目录。

m0_46309425的博客 5116

Unicode、UTF-8编码详解

Unicode 编码

lixiangchibang的博客 2万+

西电微机系统课程设计——步进电机开环控制系统设计

西电微机系统课程设计——步进电机开环控制系统设计 一、课程设计目的 1.掌握微机系统总线与各芯片管脚连接方法,提高接口扩展硬件电路的连接能力。 2.加深对 A/D 和并行接口芯片的工作方式和编程方法的理解。 3.搞懂步进电机的工作原理及控制方式,掌握开环控制系统的设计思路和实现方法。 二、课程设计的内容 手动调节电位器旋钮(0V~5V),通过 ADC0809 模拟输入水库水位 0 米~50 米,CPU收到水位信号后,根据水位高度控制步进电机(水闸)进行调节。 三、系统功能与设计要求 基本功能要求 手

OutlierLi's Blog 7540

数字IC后端设计实现之Innovus POD V2 Flow性能优化全解析

本文深入解析了数字IC后端设计中的Innovus POD V2 Flow性能优化方案。该流程通过整合place_opt_design与clock_opt_design命令,实现了布局与时钟树的协同优化,有效提升了时序收敛效率、改善了设计密度与拥塞,并显著减少了迭代次数,是应对先进工艺复杂设计的关键利器。

ik6789012的博客 1277

VC 编程ANSI环境下读写Unicode文件

VC 编程ANSI环境下读写Unicode文件2009-02-26 15:14       没有注意到文件编码的不同会产生这么多的问题,在动手以前查询了很多资料,在本博客中收藏了不少先辈的成果,在这里一并表示致敬!       关于ANSI和Unicode编码的原理在这里也不说了,主要讲下如何读写!       首先确定你的工程是采用的是什么编码环境,默认是ANSI,不

Augusdi的专栏 5227

QT日志输出终极指南:从qDebug到qFatal的完整文件记录方案

本文深入探讨了QT日志系统的企业级文件记录方案,从基础的qDebug、qWarning、qCritical、qFatal等宏的使用,到构建自定义消息处理器、实现异步写入、分级存储、日志轮转及性能监控等高级功能。旨在帮助开发者构建一个稳定、高效且易于维护的专业级日志管理架构,适用于桌面应用、嵌入式系统及服务端程序。

ik678901234的博客 927

python整理十一——读写unicode文件

对于读写unicode文件,相对比较简单:如下: #coding=utf-8 import osimport codecsdef writefile(fn, v_ls):    f = codecs.open(fn, wb, utf-8)    for i in v_ls:        f.write(i + os.linesep)

hong201的专栏 3439

五段式S型算法笔记

又因为有 v-v0= 0.5jt通式: 所以有 vm-v0= 0.5jtm 所以有4vm-4v0= 2jtm。算法1: v=2vm-v0-0.5*jt+2jt*tm-2jtm*tm。加加速度j 自己设置 已知,vmax自己设置已知;所以有4vm-4v0= 2jtm带入算法1。

qq_36658033的博客 690

Rocky Linux 9 离线环境Docker部署实战:从依赖打包到服务启动

本文提供了一份详尽的Rocky Linux 9离线环境Docker部署实战指南。针对无法访问外网的生产或内网服务器,文章详细讲解了如何在联网跳板机上下载Docker二进制包及所有系统依赖RPM包,并完成打包。随后,手把手指导在离线服务器上进行依赖安装、二进制文件部署、systemd服务配置、SELinux与防火墙调优,最终实现Docker服务的成功启动与验证。

weixin_28363123的博客 150

C++ UNICODE 文件读写相关(转载)

2012-04-15 19:34:36|  分类: windows |  标签:c++(mfc)  |举报|字号 订阅 用C++读写unicode文本 http://librawill.blogspot.com/2008/08/cunicode_2881.html 熟悉一下字符类型,char, wchar_t, TCHAR,最熟悉的char是单

程序员的自我修养_Will.zhang 3802

基于Simulink的异步电机定子磁链定向控制(SFOC)仿真

本文带你从零构建了异步电机SFOC系统​ 的完整Simulink仿真模型,实现了:✅ 搭建异步电机、逆变器、风机负载的主电路与传感器模型;✅ 用MATLAB Function实现定子磁链观测(电压模型)、坐标变换、双闭环PI控制;✅ 验证SFOC在转速跟踪(响应0.2s、超调4%)、转矩响应(恢复0.15s)中的高性能;✅ 对比RFOC,明确SFOC在参数鲁棒性(转子电阻+50%时波动<2%)上的独特优势;✅ 理解SFOC“定子磁链定向+解耦控制”的核心思想(低成本高鲁棒性驱动的工程实现)。

xiaoheshang_123的博客 396

Unicode(UTF16)文件读写终极方案

去年写过一个博客介绍了自己写的一个读写Unicode编码文件的方法,这个方法不使用系统提供的类库,使用标准C++的方法,因此很很好的可移植性。 上次写的没经过大规模的测试,这几天对这个方法进行了修改: 1支持Windows和Linux的换行符 2修改了部分代码,使之更加健壮 代码如下: /* ******************************************

Harry的专栏 3056

【异常】OpenClaw LLM Request Timeout 超时问题的快速定位与落地解决

摘要:OpenClaw系统在执行任务时频繁出现"LLM request timed out"异常。通过分析发现主模型自动调度导致响应延迟,且缺乏超时配置兜底。解决方案包括:1)将主模型切换为低延迟的豆包2.0 Lite;2)保留豆包2.0 Pro和Kimi作为备用;3)重启Gateway服务验证。优化后系统响应速度显著提升,未再出现超时异常。后续建议增加显式超时配置、优化任务拆分和Prompt指令,并建立网络监控机制。(148字)

奶爸的编程之路,也就一周冷个三天 1165

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

读写 unicode 文件

 (一)wifstream inf;inf.open(filename,ios::out);if( inf.eof()){ return;}wchar_t head[2];inf.seekg(0);inf.read(head,2);   if( (head[0] == 0xff && head[1]==0xfe )||(head[0]==0xfe&&head[1]==0xff))   { co

firebird321的专栏 1185

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

可以读写Unicode/Ansi文本文件的类

//好像C++中没有类能够读些Unicode格式的文本文件,所以我写了下面这个类。用法很简单,大家尝试几下就明白了。#pragma onceclass CStdioFileEx: public CStdioFile{public:CStdioFileEx();CStdioFileEx( LPCTSTR lpszFileName, UINT nOpenFlags );virtual BO

benny5609的专栏 1711

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

python读写ini文件的库支持unicode_Python读写unicode文件的方法

本文实例讲述了Python读写unicode文件的方法。分享给大家供大家参考。具体实现方法如下:#coding=utf-8import osimport codecsdef writefile(fn, v_ls):f = codecs.open(fn, 'wb', 'utf-8')for i in v_ls:f.write(i + os.linesep)f.close()def readfile(...

weixin_39981360的博客 146

CstdioFileEx读写UNICODE文本文件

CstdioFileEx读写UNICODE文本文件        弄了好久,都没把TXT文件乱码的问题搞定……    步骤:1.         到http://www.codeproject.com/下载CstdioFileEx类2.         使用CstdioFileEx示例代码如下:    TCHAR FileName[100];    CStdioFi

gyjdk0601的专栏 2841

UNICODE环境下读写txt文件操作

内容转载自http://blog.sina.com.cn/s/blog_5d2bad130100t0x9.html UNICODE环境下读写txt文件操作 (2011-07-26 17:40:05) 标签: 杂谈 分类:MFC程序设计 自己动手整理了一下,写了几个函数,用于UNICODE环境下对txt文本文件的操作,针对tx...

awfp80781的博客 180

VC 编程ANSI环境下读写Unicode文件和将CStdioFile类扩展,读取UNICODE文本文件

VC 编程ANSI环境下读写Unicode文件没有注意到文件编码的不同会产生这么多的问题,在动手以前查询了很多资料,在本博客中收藏了不少先辈的成果,在这里一并表示致敬!       关于ANSI和Unicode编码的原理在这里也不说了,主要讲下如何读写!       首先确定你的工程是采用的是什么编码环境,默认是ANSI,不同的字符集读写文件的差别也比较大,我这里只在ANSI环境下做的,下一步在探

阳光岛主 7658
上一篇: VC++下命名管道编程的原理及实现
下一篇: 用VC操作INI文件
scollins
博客等级 码龄19年 88粉丝 172原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值