第17课:文件的处理
直至第13课为止,我们创造的程序只是可以接受在运行时的数据,当一个程序终止时,数据也随着消失。我们是否有可能由VB程序把数据储存进硬盘,软盘,或U盘 ?答案是可以的。在这一课里,我们将了解如何创建文件及把它储存进文件里。
17.1 建立文件
要建立一个文件,可使用下列指令
Open "fileName" For Output As #fileNumber
每个文件的建立必须有一个文件名称和文件编号,以资识别。除了文件的名称,您还必须指定文件的路径。
例如:
Open "c:\My Documents\sample.txt" For Output As #1
将建立一个文本文件sample.txt在My Document 文件夹。伴随着该文件的号码是1 。如果您想要建立和保存该文件在一个驱动器了,只需更改路径,如下“
Open "A:\sample.txt" For Output As #1
如果你想创建一个HTML文件, 可用以下的指令:
Open "c:\My Documents\sample.html" For Output As # 2
17.2.1 程序示例:创建一个文本文件(文字文件)
- Private Sub create_Click()
- Dim intMsg As String
- Dim StudentName As String
- Open "c:\My Documents\sample.txt" For Output As #1
- intMsg = MsgBox("File sample.txt opened")
- StudentName = InputBox("Enter the student Name")
- Print #1, StudentName
- intMsg = MsgBox("Writing a" & StudentName & " to sample.txt ")
- Close #1
- intMsg = MsgBox("File sample.txt closed")
- End Sub
*上述计划将程序将创建一个文件sample.txt在My Document '的文件夹,并准备好接收用户输入的数据。任何用户输入的数据将被保存在这个文本文件。
17.3 读取文件
要读取之前建立的文件,您可以使用输入#声明。但是,我们只能读取根据该文件被写入时的格式。你必须根据其文件的号码来打开该文件。我们还需要使用DIM 来声明的变量。
17.3.1 范例
- Private Sub Reading_Click()
- Dim variable1 As String
- Open "c:\My Documents\sample.txt" For Input As #1
- Input #1, variable1
- Text1.Text = variable1
- Close #1
- End Sub
这一程序将打开sample.txt文件,并显示其内容在text1文本框里。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
