“常量中有换行符”的解决方法

简介

在使用MSVC编译的时候出现“常量中有换行符”这一错误,网上搜索后可知是由于文件是utf-8编码但没有带BOM导致的。解决方法有很多,因为感觉很麻烦,所以这里我使用python来给没有BOM的文件加上BOM。

代码

import os

cur_dir = os.path.dirname(__file__)
# def test():
#     u8_nb_path = os.path.join(cur_dir, 'utf-8_nobom.txt')
#     u8_b_path = os.path.join(cur_dir, 'utf-8_bom.txt')

#     u8_nb = open(u8_nb_path, "rb")
#     u8_b = open(u8_b_path, "rb")

#     print(u8_nb.read(1))
#     print(u8_nb.read(1))
#     print(u8_nb.read(1))
#     print(u8_nb.read(1))
#     print("")
#     print(u8_b.read(1))
#     print(u8_b.read(1))
#     print(u8_b.read(1))
#     print(u8_b.read(1))
#     # efbbbf
#     u8_nb.close()
#     u8_b.close()

def has_bom(content):
    return len(content) >= 3 and content[0] == 0xef \
        and content[1] == 0xbb and content[2] == 0xbf

def to_utf8_bom_f(filename):
    print("To utf8 with bom: " + filename)
    f = open(filename, "rb")
    content = f.read()
    f.close()

    if not has_bom(content):
        f = open(filename, "wb")
        # efbbbf
        bom = bytes([0xef, 0xbb, 0xbf])
        f.write(bom)
        f.write(content)
        f.close()

def to_utf8_bom_d(dir, filters=["h", "cpp", "c"]):
    for root, dirs, files in os.walk(dir):
        for file in files:
            splits = file.split('.')
            if len(splits) >= 2 and splits[-1] in filters:
                to_utf8_bom_f(os.path.join(root, file))

def main():
    src_dir = r"D:\Src\sqlitebrowser\git_repos\sqlitebrowser\src"
    to_utf8_bom_d(src_dir)

if __name__ == "__main__":
    main()

使用方法

将代码中的src_dir修改成自己的代码目录即可(根据需要修改文件filter)。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丨秋水丨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值