指定文本文件的字符格式
语法
Open filename for {Input|Output|Append} Encoding "utf-8 "|"utf-16 "|"utf-32 "|"ascii " as [#]filenum
参数
{Input | Output | Append}
filename
Encoding "utf-8 "|"utf-16 "|"utf-32 "|"ascii "
表示文件的编码类型
filenum
未使用的文件编号与打开的文件关联
说明
Encoding指定Unicode文本文件的格式,因此
Winput #和
Print #使用正确的编码。如果从
Open语句中省略,则“ascii”编码是默认值。
目前只支持小字符编码。
- “UTF-8”no
- “UTF-16”no
- “UTF-32”no
- “ascii”(默认)
例子
''这个例子将:
''1)使用utf-16编码将字符串写入文本文件
''2)显示文件的字节内容
''3)从文件中读取文本
''
'' WSTRING's也会工作,但STRING已经
''在这个例子中使用,因为并非所有的控制台都支持
'' printing WSTRING's.
''在此示例中要使用的文件的名称
Dim f As String
f = "为sample.txt"
''
Scope
Dim s As String
s = "FreeBASIC"
Print "要写的文字" + f + ":"
Print s
Print
''使用utf-16编码打开输出文件
''并打印一个短信
Open f For Output Encoding "UTF-16" As #1
''ascii字符串转换为utf-16
Print #1, s
Close #1
End Scope
''
Scope
Dim s As String, n As Integer
''打开相同的二进制文件并读取所有字节
Open f For Binary As #1
n = LOF(1)
s = Space( n )
Get #1,,s
Close #1
Print "二进制内容" + f + ":"
For i As Integer = 1 To n
Print Hex( Asc( Mid( s, i, 1 )), 2); "";
Next
Print
Print
End Scope
''
Scope
Dim s As String
''使用utf-16编码打开输入文件
''并回读该消息
Open f For Input Encoding "UTF-16" As #1
''ascii字符串从utf-16转换
Line Input #1, s
Close #1
''显示文字
Print "文字阅读" + f + ":"
Print s
Print
End Scope
输出:
Text to write to sample.txt:
FreeBASIC
Binary contents of sample.txt:
FF FE 46 00 72 00 65 00 65 00 42 00 41 00 53 00 49 00 43 00 0D 00 0A 00
Text read from sample.txt:
FreeBASIC
平台差异
- FreeBASIC的DOS端口不支持Unicode(w)字符串
方言差异
与QB差别
参考