Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2045302
  • 博文数量: 519
  • 博客积分: 10070
  • 博客等级: 上将
  • 技术积分: 3985
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-29 14:05
个人简介

只问耕耘

文章分类

全部博文(519)

文章存档

2016年(1)

2013年(5)

2011年(46)

2010年(220)

2009年(51)

2008年(39)

2007年(141)

2006年(16)

我的朋友

分类: WINDOWS

2007-09-07 13:26:20

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=”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

注意 写完文件以后一定要关闭!!!!!!!  还有就是,如果要读文件又要写文件,读完之后一定也要记得关闭,这样才能以写的方式打开。

http://blog.csdn.net/sssa2000/archive/2004/07/09/37837.aspx

阅读(5116) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~