您的位置:首页 > 编程语言 > VB

Vbscript 脚本编程关于文件的读写

2019-03-18 21:27 218 查看

Vbscript 脚本编程关于文件的读写
使用vbscript来读写文件,十分的方便,废话少说,切入正题。
1、打开文件
使用opentextfile方法
set fs =createobject(“scripting.filesystemobject”)
set ts=fs.opentextfile(“c:/1.txt”,1,true)
注意这里需要填入文件的完整路径,后面一个参数为访问模式
1为forreading
2为forwriting
8为appending
第三个参数指定如果指定文件不存在,是否创建。
2、读取文件
读取文件的方法有三个
read(x)读取x个字符
readline读取一行
readall全部读取
例如:
set fs =createobject(“scripting.filesystemobject”)
set ts=fs.opentextfile(“c:/1.txt”,1,true)
value=ts.read(20)
line=ts.readline
contents=ts.readall
这里还要介绍几个指针变量:
textstream对象的atendofstream属性。当处于文件结尾的时候这个属性返回true.我们可以用循环检测又没有到达文件末尾。例如:
set fs =createobject(“scripting.filesystemobject”)
set f=fs.getfile(“c:/1.txt”,1,false)
set ts=f.openastextstream(1,0)
do while ts.atendofstream<>true
f.read(1)
loop
还有一个属性,atendofline,如果已经到了行末尾,这个属性返回true.
Textstream对象还有两个有用的属性,column和line.
在打开一个文件后,行和列指针都被设置为1。
看一个综合的例子吧:
*read.vbs
set fs =createobject(“scripting.filesystemobject”)
set f=fs.opentextfile(“c:/1.txt”,1,true)
do while f.atendofstream<>true
data=””
for a=1 to 5
if f.atendofstream<>true then
data=data+f.readline
end if
next
dataset=dataset+1
wscript.echo “data set” &dataset & ”:” & data
loop
最后说一下在文件中跳行
skip(x) 跳过x个字符
skipline 跳过一行
用法也很简单 和前面一样,就不说了。
3、写文件
可以用forwriting和forappending方式来写
写有3各方法:
write(x)
writeline
writeblanklines(n) 写入n个空行
来看一个例子:

data=“date:” &date() & " time:"& Hour(Now)&":"&Minute(Now)&":"&Second(Now)
set fs =createobject(“scripting.filesystemobject”)
if (fs.fileexists(“c:/2.txt”)) then
set f =fs.opentextfile(“c:/2.txt”,8)
f.write data
f.writeline data
f.close
else
set f=fs.opentextfile(“c:/2.txt”,2, true)
f.writeblanklines 2
f.write data
f.close
end if

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: