Delphi判断文本文件的编码格式

Delphi2009、Delphi2010的GBK繁体转简体函数 Delphi2007之前的API繁简转函数在Delphi2009版本出现后不能用,原因在于之前版本的String默认为AnsiString,而Delphi2007之后的String默认为WideString,同样,PChar指针也就为PAnsiString,所以调用Windows API函数如:MultiByteToWideChar 会出现编译出错,原因是类型不对,也不能强制转换,以下是本人修改的网上流行的繁简转函数,测试通过,并完全正常使用! 立即下载

今天在网上看到一位老兄写的判断记事本保存的文本的四种格式的判断,觉得非常不错。

Notepad (记事本)只支持四种格式: ANSI/Unicode/Unicode big endian/UFT-8 ,在 Delphi 中如何判断与读取这些不同格式的文本呢? 首先,不同编码的文本,是根据文本的前两个字节来定义其编码格式的。
定义如下:
ANSI :          无格式定义;
Unicode :        前两个字节为 FFFE ;
Unicode big endian :  前两字节为 FEFF ; 
UTF-8 :          前两字节为 EFBB ; 

所以读写代码如下:

type
  TTextFormat=(tfAnsi, tfUnicode, tfUnicodeBigEndian, tfUtf8);

const
  TextFormatFlag: array[tfAnsi..tfUtf8] of word=($0000,$FFFE,$FEFF,$EFBB);

function WordLoHiExchange(w:Word):Word; register;
  asm XCHG AL, AH end; { TextFormat返回文本编码类型,sText未经处理的文本 }

procedure ReadTextFile(const FileName: string; var TextFormat: TTextFormat; var sText:string);
var
  w:Word;
  b:Byte;
begin
  with TFileStream.Create(FileName,fmOpenRead or fmShareDenyNone) do
    try
      Read(w,2);
      w:=WordLoHiExchange(w);//因为是以Word数据类型读取,故高低字节互换
      if w = TextFormatFlag[tfUnicode] then
        TextFormat:= tfUnicode
      else if w = TextFormatFlag[tfUnicodeBigEndian] then
        TextFormat:= tfUnicodeBigEndian
      else if w = TextFormatFlag[tfUtf8] then
      begin
        Read(b,1);//这里要注意一下,UFT-8必须要跳过三个字节。
        TextFormat:=tfUtf8;
      end
      else
      begin
        TextFormat:=tfANSI;
        Position:=0;
      end;
      SetLength(sText,Size - Position);
      ReadBuffer(sText[1],Size - Position);
    finally
      Free;
    end;
end;

经过验证ANSI和UTF-8,这个函数完全正确判定文本的格式,但是在读UTF-8文件的时候,会出现汉字乱码。事实上,我们可以利用前两个字节来判断文本类型,而通过Utf8Decode来转换。

把上面的函数简化成一个判定格式的函数,如下,为了简单,返回值使用了String:

function GetTextType(const FileName: string): String;
var
  w: Word;
  b: Byte;
begin
  with TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone) do
    try
      Read(w,2);
      w:=WordLoHiExchange(w);//因为是以Word数据类型读取,故高低字节互换
      if w = TextFormatFlag[tfUnicode] then
        Result := 'tfUnicode'
      else if w = TextFormatFlag[tfUnicodeBigEndian] then
        Result:= 'tfUnicodeBigEndian'
      else if w = TextFormatFlag[tfUtf8] then
        Result := 'tfUtf8'
      else
        Result := 'tfANSI';
    finally
      Free;
    end;
end;

感谢 http://www.delphiun.com/Article/Class6/Class7/200604/172.html文章的作者。

国产大模型高考横评:数学推理与教育落地能力实测 大模型能力评估正从开放榜单转向封闭任务的确定性验证,高考作为强逻辑、低容错、高精度的标准化考试,成为检验模型真实推理能力的理想标尺。其核心在于考察知识覆盖、步骤完整性、单位敏感性与教学对齐度,而非单纯答案正确率。数学解答题尤其凸显模型在前提校验、条件枚举与过程可控性上的差异,反映出训练数据与教育语料深度耦合带来的工程化优势。该范式已延伸至语文语感建模、英语表达习惯适配及理综跨学科缝合等场景,为智能阅卷、精准答疑和教培系统集成提供可复现、可解释、可部署的技术依据。 阅读详情

相关推荐

手把手教你用Verilog实现AT24C64的I2C读写(附完整仿真流程)

本文详细介绍了如何使用Verilog HDL设计AT24C64 EEPROM的I2C控制器,并配合ModelSim完成完整的仿真验证流程。内容涵盖I2C协议解析、Verilog状态机设计、AT24C64读写操作实现,以及仿真波形分析和调试技巧,为FPGA开发者提供了一套完整的EEPROM控制解决方案。

3c4x5z6v7b的博客 853

【delphi】判断文件的编码方式(ANSI、Unicode、UTF8、UnicodeBIG)

判断文件的编码格式(ANSI、Unicode、UTF8、UnicodeBIG)等

sensor_WU 博客 4633

不只是CPU主频:深入解析英飞凌Aurix TC3xx各外设时钟树(CAN、以太网、Flash时序如何配置)

本文深入解析英飞凌Aurix TC3xx系列微控制器的外设时钟树配置,涵盖CAN、以太网和Flash时序的优化方法。通过详细分析时钟系统架构、关键外设配置及多外设协同设计策略,帮助工程师实现高性能汽车电子控制单元(ECU)开发。特别关注系统时钟的灵活配置与EMC优化技巧,提升系统实时性和可靠性。

weixin_29189373的博客 405

Delphi 判断文件是否为UTF-8-BOM的文件

Delphi 判断文件是否为UTF-8-BOM的文件

小印丶的笔记 915

【数字逻辑电路课程设计】多功能数码管时钟VHDL+quartus II-EP1C12F324C8+源码+付费资源

我希望需要我这篇文章的是正常学习数字逻辑课程且正在设计数码管时钟的同学。我个人不推荐直接获取源代码,因此我另有一份付费资源是完整源代码;我推荐各位去研究我代码的逻辑尝试自己书写属于自己的代码,因此我保留了注释但隐去了变量。由于时间有限,我的设计不够完美,仍有很多缺陷,我将我的展望写在后面,各位可以尝试实现。我不为难同学,作为同学我理解各位设计的辛苦,因此如果有需要,私信我提供隐去敏感信息的学生证照片可直接获取源代码。

WannaFlysyx的博客 1536

摩尔线程GPU实战:5分钟搞定AI模型部署(含Docker避坑指南)

本文详细介绍了摩尔线程GPU在AI模型部署中的实战应用,包括环境配置、Docker避坑指南及性能优化技巧。通过5分钟快速部署指南,帮助开发者高效利用摩尔线程GPU进行AI模型推理,特别针对常见兼容性问题提供解决方案,显著提升部署效率。

weixin_28736335的博客 460

Delphi中文本文件Utf-8和Ansi转换

注意:没有仔细验证正确性。const  IS_TEXT_UNICODE_ASCII16 = $1;  IS_TEXT_UNICODE_REVERSE_ASCII16 = $10;  IS_TEXT_UNICODE_STATISTICS = $2;  IS_TEXT_UNICODE_REVERSE_STATISTICS = $20;  IS_TEXT_UNICODE_CONTROLS = $4;

Newweapon's Trace 4445

绝缘检测是什么? 绝缘检测原理 绝缘检测检测的是什么?那个量?电压?电流?电阻?

绝缘电阻是电气设备和电气线路最基本的绝缘指标。对于低压电气装置的交接试验,常温下电动机、配电设备和配电线路的绝缘电阻不应低于0.5MΩ(对于运行中的设备和线路,绝缘电阻不应低于1MΩ/kV)。 绝缘电阻的正确测量方法 现代生活日新月异,人们一刻也离不开电。在用电过程中就存在着用电安全问题,在电器设备中,例如电机、电缆、家用电器等。 影响因素 环境温湿度 一般材料的绝缘电阻值随环境温湿度的升高而减小。相对而言,表面电阻(率)对环境湿度比较敏感,而体电阻(率)则对温度较为敏感。 湿度增加,表面泄漏增大,导体电导

dianqicyuyan的博客 2万+

Delphi读写UTF-8、Unicode格式文本文件

 // UTF-8文件写入函数procedure SaveUTFFile(const FileName: string; S: string; WriteHeader: Boolean = True);var  MemStream: TMemoryStream;  HeaderStr: String;begin  if S = then Exit;   MemStream := TM

missmecn的专栏 5059

【电容/电感】电路板会“滋滋”的响,我们称它为啸叫

一、啸叫的起源 大部分硬件工程师应该都遇到过,PCBA上电后出现“滋滋滋”的叫声,其声响或大或小,或时有时无,或深沉或刺耳,或变化无常者皆有。该现象我们称为“啸叫”,一般分为电感啸叫和电容啸叫。

云轩阁 6万+

独立游戏之路:Tap篇 -- 个人开发者上架TapTap步骤和注意事项

作为一名游戏开发者,将自己的独立游戏上架到 TapTap 平台是一个不错的选择。TapTap 是一个拥有大量用户的游戏社区平台,上架游戏可以让更多的玩家发现和体验你的游戏。TapTap 是一个游戏社区平台,用户可以在平台上下载和分享游戏。TapTap 拥有大量的用户,并且用户活跃度高,这为独立游戏开发者提供了一个很好的展示和推广平台。进入TapTap开发者服务后台。

陈言必行 -- Unity游戏开发领域优质博主 6496

Delphi2010中保存UTF8/Unicode编码文件的问题

使用Delphi2010中的TStrings或Memo的SaveToFile方法保存UTF8/Unicode编码的字符串时,保存后丢失编码信息,仔细查看,原来在保存时增加了编码设置: aStrings.SaveToFile(aFileName,TEncoding.Unicode) ;//可以是TEncoding.UTF8,根据需要   另: unicode文本文件:头两个字符分别是FF  ...

weixin_34367845的博客 426

基于生存结局(生存分析/COX回归)的中介效应分析

① 建立观察变量OVB和中介变量MVB的回归模型(注意:这里根据mediation包的介绍,需要构建的是probit模型,而不是logist回归模型,网上有很多的代码用的logistic回归,结果自己跑的时候发现报错,我在这里陷了很久;为了方便演示,我们生成了一个协变量(Age)、一个连续型观察变量(liaOVC)、一个二分类观察变量(OVB)、一个连续型中介变量(MVC)、一个二分类中介变量(MVB)以及最后的结局变量(生存时间[time],生存结局[stats])。

m0_61863309的博客 1万+

Delphi 判断文本文件的编码格式并读取内容

这里指的文本是用于Windows系统中的扩展名为.txt的文件。 Notepad(记事本)只支持四种格式:ANSI/Unicode/Unicode big endian/UFT-8,在Delphi中如何判断与读取这些不同格式的文本呢? 首先,不同编码的文本,是根据文本的前两个字节来定义其编码格式的。定义如下: ANSI: 无格式定义; Unicode: 前两个字节为FFFE; Unicode bi...

百万软件 1601

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

InTheHand.Net.Personal+BlueTooth4,蓝牙开发

项目中有蓝牙开发的必备dll,现在网上相关的文档博客不少,有的说的多有的说少,但是却很少有这两个dll,分享一下。

Delphi 判断文本文件的编码格式

不同编码的文本,是根据文本的前两个字节来定义其编码格式的。定义如下: ANSI: 无格式定义; Unicode: 前两个字节为FFFE; Unicode big endian: 前两字节为FEFF; UTF-8: 前两字节为EFBB; type   TTextFormat=(tfAnsi,tfUnicode,tfUnicodeBigEndian,tfUtf8); const

人体运动、生物特征、高性能移动计算、人性化智能交互 1800

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

查看文件的编码格式的方法

这里指的文本是用于Windows系统中的扩展名为.txt的文件。Notepad(记事本)只支持四种格式:ANSI/Unicode/Unicode big endian/UFT-8,在Delphi中如何判断与读取这些不同格式的文本呢?首先,不同编码的文本,是根据文本的前两个字节来定义其编码格式的。定义如下:ANSI:        无格式定义; Unicode:       前两个字节为FFFE; U

xcdsy@aliyun.com 5414

深度学习工具包 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")

如何判断文本文件的编码格式?

这里指的文本是用于Windows系统中的扩展名为.txt的文件。Notepad(记事本)只支持四种格式:ANSI/Unicode/Unicode big endian/UFT-8,在Delphi中如何判断与读取这些不同格式的文本呢?首先,不同编码的文本,是根据文本的前两个字节来定义其编码格式的。定义如下:ANSI:        无格式定义;Unicode:       前两个字节为FFFE;Un

smokingroom的专栏 1697

delphi 如何判断编码格式,解决乱码问题

前阵子因为需要用到idhttp下载网页,然而令人很生气的是,他下载的html源码是乱码的,这样子是没有办法使用的,所以就必须要把他进行编码格式转换,然而令人困扰的是,他是什么格式,又该怎么转,转成什么格式,这都是问题,转成什么格式,自然是ansi ,可以正常人看的懂的才行了,该怎么转,就必须先知道原先是什么格式了,,他是什么格式,这个就不好办了           网页格式,不外乎三种,utf8

忽悠 1万+

用Delphi写一个UTF8编码格式的文本文件

... var f: TextFile; begin AssignFile(f, 'test.txt'); Rewrite(f); write(f, #$EF+#$BB+#$BF); // UTF-8 BOM,关键就是写入这个UTF-8的BOM, BOM 是 Bype Order Mark 的缩写。 writeln(f, UTF8Encode('中文')); CloseF

一刀日记 9955

Delphi 处理 Windows 下的文本文件的 Unicode 的问题

用 Delphi 写了个程序,在 Windows 底下,加载一个文本文件,查里面的字符串。 文本文件,随手用 Windows 的记事本编辑了一个。 程序运行起来,测试这个文本文件,正常。 但是,某天我把 Windows 的系统语言设置为英语,再次跑这个程序,加载上述文本文件时,出错了,查不到应该有的字符串了。 用记事本打开那个文本文件一看,里面的中文字符串是乱码。这才想起来,Windows...

pcplayer的博客 1691

查看文本文件编码格式

这里指的文本是用于Windows系统中的扩展名为.txt的文件。 Notepad(记事本)只支持四种格式:ANSI/Unicode/Unicode big endian/UFT-8, 在Delphi中如何判断与读取这些不同格式的文本呢? 首先,不同编码的文本,是根据文本的前两个字节来定义其编码格式的。定义如下: ANSI:        无格式定义; Unicod...

weixin_34117211的博客 1277
上一篇: Delphi中文本文件Utf-8和Ansi转换
下一篇: Side-by-side Assemblies
newweapon
博客等级 码龄21年 45粉丝 83原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址