python - 将头文件 #ifndef 添加到当前目录下的 C 头文件中

标签 python c shell c-preprocessor

在当前目录下,所有的C头文件(*.h)都不包含预处理器宏

#ifndef FILENAME_H
#define FILENAME_H
...
#endif

,手动将它们添加到每个标题中太繁琐了。如何通过 python 或 shell 自动执行此操作?

最佳答案

根据科迪的回答,我实现了guardHeader.py:

  1 #!/usr/bin/python3
  2
  3 import glob,os,sys
  4
  5 global search_dir
  6
  7 def clearContent(pfile):
  8     pfile.seek(0)
  9     pfile.truncate()
 10
 11 def guard(fileName):
 12     file = open(fileName, 'r+')
 13     content = file.read()
 14
 15     fileNameUp = fileName.split(".")[0].upper() + '_H'
 16     guardBegin = '#ifndef ' + fileNameUp + '\n'    \
 17             '#define ' + fileNameUp + '\n\n'
 18     guardEnd = '\n#endif'
 19     newContent = guardBegin + content + guardEnd
 20
 21     clearContent(file)
 22     file.write(newContent)
 23
 24 if __name__ == '__main__':
 25     if len(sys.argv) == 1:
 26         print('Please provide a directory')
 27     else:
 28         search_dir = sys.argv[1]
 29
 30     # enter search directory
 31     os.chdir(search_dir)
 32
 33     for file in glob.glob("*.h"):
 34         guard(file)

关于python - 将头文件 #ifndef 添加到当前目录下的 C 头文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38778409/

相关文章:

python - 在 CPython 中搜索 DLL 的变量 PATH

c - 为什么这个特定的代码会抛出异常?

bash - 如何在heroku procfile中编写多行命令

c - c中电话号码的正则表达式

c - 为什么微软将类型CHAR定义为char,将宏CONST定义为const?

linux - BASH:输入期间的 Ctrl+C 会中断当前终端

linux - 使用 Linux shell 编辑文本文件中的行

python - 更快的字节数组列表理解/转换?

python - 为什么 "pip install lxml"不使用提供的轮子,而是尝试编译?

python - 从字典中查找与今天日期最接近的日期