文件读写
程序总离不开数据的输入输出,除了键盘鼠标最重要的媒介就是磁盘文件
而且无论什么语言,如果不支持二进制文件的操作,就算不上是强大的语言
文件读写常用的有下面的语句和函数:
Open FreeFile Input Get Put Lof Loc EOF Close ...
要操作一个文件我们必须先打开它:
Open 文件名(全路径) For 模式 Access 读/写 Lock 读/写 As #文件号 Len = 长度
文件名是能够指明文件位置的字符串常量或者表达式,如:
"c:/1.txt",Text1.Text,strFileName,Label1.Caption,List1.List(0),List1.Text
模式是打开进行操作的类型,如:
Input(输入),Output(输出),Append(追加),Random(随机),Binary(二进制)
Access 是指明读写的类型(方式):读 或 写 这部分可以省略
Lock 指明不能进行的操作,如Lock Write 就使得其它进程不能对该文件写入数据,也可以省略
#文件号 标识文件的东西,究竟是什么不需要知道,1-511之间的值,可以用FreeFile返回可用的
文件号,如:
Dim f As Integer
f = FreeFile
后面还有个Len 就是制定文件读写的长度,小于或等于 32,767(字节)的一个数。对于用随机
访问方式打开的文件,该值就是记录长度。对于顺序文件,该值就是缓冲字符数。可以省略,且如
果是二进制模式,Len 部分是无效的,写多少都没用.
文件名:程序目录下 Test.txt文件
文本框:Text1
按钮:Command1
点击Command1,把Test.txt的内容读到Text1
Private Sub Command1_Click()
Dim s As String
Open App.Path & "/Test.txt" For Input As #1
Do While Not EOF(1)
Line Input #1,s
Text1.Text = Text1.Text & s & vbCrLf
Loop
Close #1
End Sub
逐行输入是最常用的输入,其他的要各位新手多摸索了
下面演示一种自定义文件类型的文档读写,这里也顺便演示函数/过程的写法
设定文档文件头WBX三个字节,第四字节为加密的密文
'读取函数 Public Function ReadFile(Byval strFileName As String) As String Dim st As String, bXor As Byte, i As Integer Dim f As Integer, b() As Byte On Error Goto ErrHandle If Dir(strFileName) = "" Then Exit Function f = FreeFile Redim b(2) Open strFileName For Binary As #f Get #f,,b(0) Get #f,,b(1) Get #f,,b(2) If Chr(b(0)) & Chr(b(1)) & Chr(b(2)) <> "WBX" Then Msgbox "不是支持的文件类型!",vbExclamation ,"类型错误" Exit Function End If Get #f,,bXor Redim b(Lof(f) - 4) For i = 4 To Lof(f) Get #f,,b(i) b(i) = b(i) Xor bXor st = st & b(i) Next i Close #f ReadFile = st Exit Function ErrHandle: Msgbox "文件打开过程中出现了不可预料错误.",vbCritical End Function '保存函数 Public Function WriteFile(Byval strFileName As String, Byval StrText As String, Optional Byval bXor As Byte) As Boolean Dim bt As Boolean, i As Integer Dim f As Integer, b() As Byte On Error Goto ErrHandle f = FreeFile Open strFileName For Binary As #f Put #f,,CByte(Asc("W")) Put #f,,CByte(Asc("B")) Put #f,,CByte(Asc("X")) Put #f,,bXor b = StrText For i = 0 To Ubound(b) Put #f,,b(i) Xor bXor Next i Close #f WriteFile = True Exit Function ErrHandle: Msgbox "文件打开过程中出现了不可预料错误.",vbCritical End Function
读取 只要传递 文件名 和加密码就可以了
比如
Private Sub Command1_Click()
Text1.Text = ReadFile(App.Path & "/Test.wbx")
'Text1.Text = ReadFile(CommonDialog1.FileName)
End Sub
Private Sub Command2_Click()
If WriteFile(App.Path & "/Test.wbx",Text1.Text) = True Then
Msgbox "保存完毕!"
Else
Msgbox "保存失败!"
End If
End Sub
到这个程度,很多东西只能靠意会,靠摸索,考的是程序员的思考能力!
要把某一种语言讲透彻那是学者的事情了
本文详细介绍了文件读写的基本概念及常用方法,包括如何使用不同模式打开文件、读写操作的具体实现,以及通过示例演示了自定义文件类型的文档读写过程。
1116

被折叠的 条评论
为什么被折叠?



