python消除C语言注释

用python写的小程序,可以消除单行注释//,多行注释/* .....*/


def commentsEliminate1(file1,file2):
    # 获取行数,存储在res
    file = open(file1, "r+")
    res = len(file.readlines())
    # print(res)
    file.close()

    f1 = open(file1, "r+")  # 读取源文件
    f2 = open(file2, "a+")  # 写向目标文件
    flag = 0  # 标记位,标记是否进入多行注释/* */
    while res > 0:
        res -= 1
        code = f1.readline()  # 读取文件
        length = len(code)  # 每行字符数
        for i in range(length):
            # 单行注释//
            if flag == 0 and code[i] == '/' and code[i + 1] == '/':
                f2.write("\n")
                break
            # 多行注释/* .....  */
            elif flag == 0 and code[i] == '/' and code[i + 1] == '*':
                flag = 1
            elif flag == 1 and code[i] == '*' and code[i + 1] == '/':
                flag = 0
                break
            elif flag == 1:
                continue
            elif flag == 0:
                f2.write(code[i])
    f1.close()
    f2.close()
    print("Success")

if __name__ == '__main__':
    file1="test.c"
    file2="test1.c"
    commentsEliminate1(file1,file2)

源程序:

 处理过的:

 

  • 12
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值