使用opentextfile方法app
set fs =createobject(“scripting.filesystemobject”)oop
set ts=fs.opentextfile(“c:\1.txt”,1,true)spa
注意这里须要填入文件的完整路径,后面一个参数为访问模式指针
1为forreadingcode
2为forwriting对象
8为appendingip
第三个参数指定若是指定文件不存在,是否建立。get
读取文件的方法有三个it
read(x)读取x个字符ast
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。
看一个综合的例子吧:
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 跳过一行
用法也很简单 和前面同样,就不说了。
能够用forwriting和forappending方式来写
写有3各方法:
write(x)
writeline
writeblanklines(n) 写入n个空行
来看一个例子:
data=”hello, I like script programing” 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
注意 写完文件之后必定要关闭!!!!!!! 还有就是,若是要读文件又要写文件,读完以后必定也要记得关闭,这样才能以写的方式打开。