FreeBASIC unicode 操作(源文件读取、输入输出)总结
代码源文件读取
var s = @"test万国码"
/' 也可以用string '/
print *s
编码:ASCII 正常
编码:UTF8 乱码
- 解决方法:转义
print !"\u4e07\u56fd\u7801"
编码:UTF8(BOM) 正常
编码:UTF16(BE) 正常
编码:UTF16(LB) 正常
文件I/O
utf8的文件名
用c运行时可以解决,fb的open并不支持utf8
code by dodicat
#include once "crt.bi"
#include once "file.bi"
Function FileLength(filename As wstring Ptr)As Long
Dim As wstring * 4 k="r"
Var fp=_wfopen(filename,@k)
If fp = 0 Then Print "Error opening file":Sleep:End
fseek(fp, 0, SEEK_END)
Var length=ftell(fp)
fclose(fp)
Return(length)
End Function
function LoadFile (filename As wString Ptr)as string
Var l=Filelength(filename)
dim as string content =String(l,0)
Dim As wstring * 4 k="rb"
Var fp= _wfopen(filename,@k)
If fp = 0 Then Print "Error loading file ";filename:Sleep:End
fread(@content[0], 1,l, fp)
fclose(fp)
return content
End function
print LoadFile("测试.txt")
以非utf8方式保存,或者&h 16进制方式保存
含unicode的文件内容
如果是utf8用utf8tostr()转换即可
#include once "wndows.bi"
#include Once "utf_conv.bi"
Function Utf8toStr(Utf8str as String) as String
Dim eLen As Integer = Len(Utf8str)
If eLen = 0 Then Return ""
Dim wsStr() As UByte ' = CAllocate(eLen * 2 + 2) '+2 是为了最后空出2个00 为宽字符结尾
ReDim wsStr(eLen * 2 + 2)
UTFToWChar(UTF_ENCOD_UTF8, StrPtr(Utf8str), Cast(WString Ptr,@wsStr(0)), @eLen)
Dim ZStr as String
ZStr = String(eLen * 2 + 2, 0)
Dim ZStrLen as Integer = WideCharToMultiByte(936/'自己改'/, 0, Cast(WString Ptr,@wsStr(0)), eLen, StrPtr(ZStr), eLen * 2 + 2, Null, Null)
If ZStrLen Then Function = Left(ZStr, ZStrLen)
' Deallocate wsStr
End Function
本文来自博客园,作者:Ruptpsych,转载请注明原文链接:https://www.cnblogs.com/obj-a/p/16392385.html