python消除C语言注释

这是一个使用Python编写的程序,其功能是读取C语言源代码文件,移除其中的单行注释(//)和多行注释(/*...*/),并将处理后的代码保存到新的文件中。程序通过读取源文件的每一行,检查是否存在注释并进行相应的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用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)

源程序:

 处理过的:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值