Skip to content

ENCODING


指定文本文件的字符格式

语法

open filename for {Input|Output|Append} Encoding "utf-8"|"utf-16"|"utf-32"|"ascii" as [#]filenum

参数

filename for

InputOutputAppend 方式打开的文件名

Encoding "utf-8"|"utf-16"|"utf-32"|"ascii"

指示文件的编码类型

filenum

与打开文件关联的未使用文件号

说明

Encoding 指定Unicode文本文件的格式,使 Winput #Print # 使用正确的编码。若在 Open 语句中省略,默认编码为"ascii"。

目前仅支持小端字符编码:

  • "utf8"
  • "utf16"
  • "utf32"
  • "ascii"(默认)

示例

start GeSHi

vb
'' This example will:
'' 1) Write a string to a text file with utf-16 encoding
'' 2) Display the byte contents of the file
'' 3) Read the text back from the file
''
'' WSTRING's will work as well but STRING has been
'' used in this example since not all consoles support
'' printing WSTRING's.

'' The name of the file to use in this example
Dim f As String
f = "sample.txt"

''
Scope
  Dim s As String
  s = "FreeBASIC"

  Print "Text to write to " + f + ":"
  Print s
  Print

  '' open a file for output using utf-16 encoding
  '' and print a short message
  Open f For Output Encoding "utf-16" As #1

  '' The ascii string is converted to utf-16
  Print #1, s
  Close #1
End Scope

''
Scope
  Dim s As String, n As LongInt

  '' open the same file for binary and read all the bytes
  Open f For Binary As #1
  n = LOF(1)
  s = Space( n )
  Get #1,,s
  Close #1
 
  Print "Binary contents of " + 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
 
  '' open a file for input using utf-16 encoding
  '' and read back the message
  Open f For Input Encoding "utf-16" As #1

  '' The ascii string is converted from utf-16
  Line Input #1, s
  Close #1

  '' Display the text
  Print "Text read from " + f + ":"
  Print s
  Print
End Scope

end GeSHi

输出:

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)字符串

方言差异

  • -lang qb 方言中不可用,除非使用别名 __Encoding 引用。

与 QB 的差异

  • QB 不支持 Unicode

另请参阅

  • Open

返回 目录

基于 FreeBASIC 官方文档翻译 如有侵权请联系我们删除
FreeBASIC 是开源项目,与微软公司无隶属关系