从网上下下来的代码,一编译老是出现:
warning C4819: The file contains a character that cannot be represented in the current code page (936). Save the file in Unicode format to prevent data loss
另我感觉实在不爽得很,因为就一个头文件,就出现几百个这样的警告。采用warning disable的方式应该也不怎么好,所以写了个utf8文件转换器。
用c++做这玩意,实在没意思,大才小用,所以用python做了一个。
import chardet
import tempfile
import os
import shutil
import sys
def convertUtf8(filename):
f=open(filename,'r')
t='' #存放文件的数据
try:
for line in f:
t+=line #所文件读到t里面
finally:
f.close()
encodeing =chardet.detect(t)['encoding']
if not encodeing =='utf-8':
print 'file encode',encodeing
wf=open(filename,'wr')
wf.write(unicode(t,encodeing).encode('utf-8')) #编码
wf.close()
import tempfile
import os
import shutil
import sys
def convertUtf8(filename):
f=open(filename,'r')
t='' #存放文件的数据
try:
for line in f:
t+=line #所文件读到t里面
finally:
f.close()
encodeing =chardet.detect(t)['encoding']
if not encodeing =='utf-8':
print 'file encode',encodeing
wf=open(filename,'wr')
wf.write(unicode(t,encodeing).encode('utf-8')) #编码
wf.close()
if __name__=="__main__":
filename = sys.argv[1] #第一个参数为文件名
convertUtf8(filename)
filename = sys.argv[1] #第一个参数为文件名
convertUtf8(filename)
如果你也有我这样烦恼就用用吧。
lixiaomail
2008-07-23