前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >递归修改当前目录 .cpp、.h、.md 文件为 UTF8 或 UTF8-BOM 格式

递归修改当前目录 .cpp、.h、.md 文件为 UTF8 或 UTF8-BOM 格式

作者头像
我与梦想有个约会
发布2023-10-21 15:34:15
2520
发布2023-10-21 15:34:15
举报
文章被收录于专栏:jiajia_dengjiajia_deng

有些代码目录下的文件格式不同,会导致一些编译错误或者中文出现错误等等问题,下面脚本就是解决这个问题而生的。使用 Autoit3 编译脚本后放到你要转换的目录中,运行脚本会转换所有 .cpp、.h、.md 文件为 UTF8 格式,如果你希望修改成 UTF8-BOM 格式,可以将 FO_UTF8_NOBOM 修改为 FO_UTF8

代码语言:javascript
复制
#include <Array.au3> ; Only required to display the arrays
#include <File.au3>
#include <MsgBoxConstants.au3>
#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>

$aArray = _FileListToArrayRec(@ScriptDir, "*.cpp;*.h;*.md", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_SORT)
_ArrayDisplay($aArray, "待转换列表.")

For $i = 0 To $aArray[0]
    _Convert2UTF8(@ScriptDir & '\' & $aArray[$i])
Next

Func _Convert2UTF8($sFilePath)
    Local $hInputFile = FileOpen($sFilePath)
    Local $s_Txt = FileRead($hInputFile)
    FileClose($hInputFile)
    Local $hOutputFile = FileOpen($sFilePath, $FO_OVERWRITE + $FO_UTF8_NOBOM)
    FileWrite($hOutputFile, $s_Txt)
    FileClose($hOutputFile)
EndFunc

新增 Python3 版本的脚本,可以通过命令 pythonfile.py -e utf-8-sigpythonfile.py -e utf-8 对当前目录下文件进行转换。pythonfile.py 是你保存的文件名。执行前需要 pip install chardet 安装包。

代码语言:javascript
复制
import argparse
import chardet
import codecs
import os

parser = argparse.ArgumentParser(description='convert encoding')
parser.add_argument('-e', '--encoding', dest='encoding', metavar=None, required=True, action='store', help='encoding')
args = parser.parse_args()

for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        if name.endswith(".cpp") or name.endswith(".h") or name.endswith(".md"):
            content = codecs.open(os.path.join(root, name), 'rb').read()
            encoding = chardet.detect(content)
            if encoding["encoding"] is None:
                continue
            if encoding["encoding"].upper() != args.encoding.upper():
                print(encoding["encoding"], "\t", os.path.join(root, name))
                content = content.decode(encoding["encoding"], 'ignore')
                codecs.open(os.path.join(root, name), 'w', encoding=args.encoding).write(content)
本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-12-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com