windows 下文件的大小写不敏感, 在移植windows的C/CPP程序到linux上常常报告头文件找不到
大多数情况是这样的:一个头文件名为HeadFile.h 在windows下 你可以这么写 #include "HeadFile.h" #include "headfile.h" #include "heAdfile.h" #include "HEADFILE.H" 等等 ,他们在windows上都是OK的 ,但linux 下用ext 的文件系统的话他们则是大小写敏感的,显然就会出现导致找不到头文件的情况。
下面用python脚本实现 对目录中的所有h hpp c cpp 文件中的include 做检查,将生成一个正确的副本。
以下是代码(欢迎使用,如果发现BUG 可以写mail给我:hzdengxu@163.com):
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author <Dengxu>
# Bug Report To <e-mail:hzdengxu@163.com>
# Blogs <http://blog.youkuaiyun.com/dengxu11>
# Life's short. Python more!
##########################################
import sys
import os
import re
headfiles = {}
allheadfiles = []
pt = re.compile(r'(#\w*include\s+)("|<)([\w\.]+)("|>)')
def init(p):
for (root, dirs, files) in os.walk(p):
for f in files:
if f.endswith(('.h', '.hpp')):
allheadfiles.append(f)
headfiles[f.lower()] = f
def doparse(fname, fpr, fpw):
counter = 0;
while True:
line = fpr.readline()
if len(line) == 0:
break
counter += 1
match = pt.search(line)
if match is not None:
hfi = match.group(3)
if hfi not in allheadfiles:
lhfi = hfi.lower()
if lhfi in headfiles:
good = headfiles[lhfi]
print 'File %s, Line %d is not correct! Transform it: [%s] => [%s]' % (fname, counter, hfi, good)
line = line.replace(hfi, good, 1)
fpw.write(line)
def parse_curr(preffix):
preffix = os.path.normpath(preffix)
for (root, dirs, files) in os.walk('.'):
for f in files:
if f.endswith(('.h', '.hpp', '.cpp', '.c')):
srcfile = os.sep.join((root, f))
desfile = os.sep.join((preffix, root, f))
d = os.path.dirname(desfile)
if not os.path.exists(d):
os.system('mkdir -p ' + d)
fpr = file(srcfile, 'rb')
fpw = file(desfile, 'wb')
doparse(srcfile, fpr, fpw)
fpw.close()
fpr.close()
def main():
path = '.'
args_count = len(sys.argv)
if args_count == 2:
path = sys.argv[1]
if not os.path.exists(path):
print "Invalid arguments!!"
exit(1)
abspath = os.path.abspath(path);
if (abspath == '/'):
print "Invalid arguments can not be toppest path!!"
exit(1)
filename = os.path.basename(abspath)
os.chdir(path)
init(path)
parse_curr(os.sep.join(('..', 'OK', filename)))
if __name__ == '__main__':
main()