GN2312批量转换为UTF-8

嵌入式项目的源码有的是GB2312格式的,有的是UTF-8格式,想统一转换为UTF-8格式
让AI写了个脚本如下:
1.powershell脚本执行转换

# 获取脚本所在文件夹路径
$folderPath = Split-Path -Parent $MyInvocation.MyCommand.Definition

# 获取目标文件夹及其子文件夹下的所有.c和.h文件
$files = Get-ChildItem -Path $folderPath -Filter *.c -Recurse
$files += Get-ChildItem -Path $folderPath -Filter *.h -Recurse

# 遍历所有文件并进行编码转换
foreach ($file in $files) {
    # 读取文件内容(假设原文件是GB2312编码)
    $content = Get-Content -Path $file.FullName -Encoding Default

    # 将内容保存为UTF-8编码(无BOM)
    $content | Set-Content -Path $file.FullName -Encoding UTF8
}

Write-Host "所有.c和.h文件已成功转换为UTF-8编码!"

2.cmd脚本调用powershell

@echo off
:: 设置脚本路径为当前目录下的 trans.ps1
set "ScriptPath=%~dp0trans.ps1"

:: 检查脚本文件是否存在
if not exist "%ScriptPath%" (
    echo PowerShell脚本文件 trans.ps1 不存在,请检查路径!
    pause
    exit /b
)

:: 运行 PowerShell 脚本
PowerShell -NoProfile -ExecutionPolicy Bypass -File "%ScriptPath%"

:: 按任意键退出
pause

创建以上两个文件,powershell脚本名称为trans.ps1,cmd脚本名称为runscript.bat,然后把它俩丢到想转换的目录下面,双击cmd脚本就行了,它会自动转换当前目录及所有子目录下所有.c和.h文件的格式到UTF-8。
记得两个脚本都保存为ANSI格式

posted @ 2026-01-03 18:22  路星遥  阅读(0)  评论(0)    收藏  举报