在当前目录下,所有的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/