Open method Read and write files

Source: Internet
Author: User

VB to read and write files using the Open method

(i) Open and close files

1. Sequential files

To open the sequential file, we can use the Open statement. It has the following format:

Open pathname for [Input | Output | Append] as [#]filenumber [Len = buffersize]

Description

(1) Parameter pathname indicates the name of the file to be opened, and the file name can contain a drive and directory

(2) Input Output and append are used to set how sequential files are opened. Where input indicates that data is read from an open file. When you open a file this way, the file must exist, or an error will result. Output indicates that data is written to the open file. When you open a file this way, the data in the file will be overwritten and the new data will be written from the beginning of the file. If the file does not exist, a new file is created. Append represents the addition of data to an open file. When opened in this way, the data in the file will be retained and the new data will be added from the beginning of the file. If the file does not exist, a new file is created.

(3) The As[#]filenumber clause is used to specify a file number for an open file. When you read and write to a file, you use the file number to represent the file. The file number is an integer between 1~511, which can be either a number or a variable. You can omit it.

(4) When copying data between files and programs, the LEN=BUFFERSIZE clause specifies the number of characters in the buffer.

For example:

Open App.Path + "/test.dat" for Output as 1

Open App.Path + "/test.dat" for Output as 1

These two lines of code create a text file named Test.dat in the directory where the current application is located, with the assigned file number 1.

Open App.Path + "/test.dat" for Input as [#]filenumber

This statement reads data from a text file.

Open App.Path + "/test.dat" for Append as [#]filenumber

This statement adds data like a text file

2. Random files

Before you manipulate random files, you must first define the record types that are used to hold the data items. The record is a user-defined data type that is the basic structure for storing data in random files. For example:

Type Student
No as Integer
Name as String * 20
Age as Integer
End Type

Dim Stud as Student ' defines a variable that can hold student material

In a random file, all the data is saved to several records of the student type, and the data read from the random file can be stored in the variable stud.

Then we can open and read and write the file. The following is the syntax format for opening random files:

Open filename for Random as [#]filenumber Len = Reclength

Description

(1) The parameter filename and filenumber respectively indicate the file name or number.

(2) The keyword random indicates that a random file is open

(3) The Len clause is used to set the record length, which is specified by the parameter reclength. The value of reclength must be greater than 0. and must be consistent with the length of the record structure you define. The method for calculating the record length is to add the length of each element in the record structure. For example, the length of the previously declared student should be 2+20+2=24 bytes.

The way to open a random file with a record type of student is:

Open "C:/student.txt" for Random as #1 Len = 25

3. binary files

The syntax for opening binary files is as follows:

Open pathname for Binary as [#]filenumber

Description

(1) The parameter filename and filenumber respectively indicate the file name or number.

(2) The keyword binary means that the binary file is open

(3) For binary files, you cannot specify a byte length. Each open binary has its own pointer, and the file pointer is a numeric value that points to the location in the next read-write operation's file. Each "position" in the binary corresponds to a data byte, so there are 1 to n locations for files with n bytes .

We can use the Seek () function to return the current file pointer position (that is, the next byte to read and write), and the LOC () function to return the byte position of the last read and write, unless the LOC () return value is always 1 smaller than the Seek (). Let's look at the following example:

Open "Student.txt" for Binary as #1

The statement opens the Student.txt file in a binary way.


(ii) Read the document

1. Sequential files

There are three ways to read sequential files:

(1) Line Input # statement

The statement reads a row of data from an open sequential file. The line here refers to all the data from the current pointer position to the carriage return or carriage return line-feed character. The syntax format of the line Input # statement is as follows:

Line Input # file number, variable number

Note: "File number" is the file number used to open the file; "Variable number" is used to hold one or more variables to read the data, if there are multiple variables, the middle with a space split open. The input# statement reads a field of the file for each variable in the argument list and stores the read-out field in a variable. The statement can only be ordered from the first domain until it reads the desired domain.

Take a look at the following code:

Dim StrLine as String

Open "C:/vb/test.txt" for Input as #1

Do Until EOF (1)
Line Input #1, StrLine
Text1. Text = Text1. Text + strLine + CHR + chr (10)
Loop

Close #1

This section of code reads a file into a text box one line at a time.

(2) Input function

This function can read a string of a specified length from a sequential file at one time. Specifically, you read the specified number of characters starting at the current location of the file, and then return them. The input function can read a variety of characters, including line feeds, carriage returns, whitespace, and so on. Here is the syntax format for it:

Variable = Input (string length, file number)

For example, to read 12 characters from an open file and copy it to the variable file, we can write:

File = Input (12,filenum)

If you want to copy the entire file to a variable, use the InputB function to copy the bytes from the file to the variable. Because the INPUTB function returns an ASCII string, the ASCII string must be converted to a Unicode string using the Strcopy function. The code is as follows:

File = Strcopy (Input (LOF (filenanum), FileNum), Vbunicode)

(3) Input # statement

Input #语句可以从文件中同时向多个变量内读入数据, and the data read in can be of different types.
 
The following makes its syntax format:

Input # File number, variable list

For example, we want to write the data in the file Student.txt, here is the code:

Open "Student.txt" for Output as #filenum

Write #filenum, "Zhang San", "First grade", 14
Write #filenum, "John Doe", "Vocational School", 18

Dim name As String, Nianji as String, age as Integer
Dim name1 As String, Nianji1 as String, age1 as Integer
Open "Student.txt" for Input as #filenum
Input #filenum, Name, Nianji, age
Input #filenum, name1, Nianji1, Age1
Close #filenum

Execution Result:

Name= "Zhang San", Nianji = "First grade", Age =14

Name= "John Doe", Nianji = "Vocational School", age =18

2. Random files

Reading random files is possible by using the Get # statement, where the data is read from a specified record in a file and stored in a user-defined variable.

Syntax format: Get # filenum, [Recnum],usertype

Description

(1) FileNum is the file number to open; Recnum is the record number to read, and if omitted, the next record is read

(2) Usertype is a user-defined data type variable that is used to store read data.

Here is an example:

Get # 1,5,student

The statement reads the 5th record in a file with a file number of 1.

3. binary files

The method of reading and writing binary files is basically the same as reading and writing random files, the following is the related statement format and its description:

Format: Get [#]filenumber, [Pos], Var

Function: Use binary mode, start reading from the location specified in the file, data of the given variable length

Description

(1) FileNumber is a file number that is opened in binary mode.

(2) POS is used to specify the byte position at which the read-write operation occurs, and, if omitted, the current file pointer position.

(3) var is a variable that is used to store the read data. The statement automatically reads the appropriate file based on the length of bytes contained in the Var variable, and if Var is a variable-length string variable, the number of bytes transferred equals the current number of bytes in var. for file length judgment we can use the LOF () function, Eof () function to check the end position of the file.

The following code copies the Studert.txt file to the Student1.txt file

Dim ar as String * 1, I as Integer
Open "C:/student.txt" for Binary as #1
Open "C:/student2.txt" for Binary as #2
For i = 1 to LOF (1)
Get #1,, AR
Put #2, AR
Next I

Close #1, #2


(c) Writing of documents

1. Sequential files

Write order file We can use write # and print #语句向一个已经打开的文件中写入数据.

Here are their formats and descriptions:

The syntax format for Print #:

Print # File number, variable list

For example, write the text in the text box to a file with the following code:

Open "file.txt" for Output as #filenum

Input #filenum, Text1.Text

Syntax format for Write # statements:

Write # File number, variable list

Description: Information written with the Write # statement facilitates later #语句来读取数据 with input because the write #语句自动将写入到文件中的信息用逗号分开 and double quotation marks for string data. For example:

Open "Student.txt" for Output as #filenum

Write #filenum, "Zhang San", "First grade", 14
Write #filenum, "John Doe", "Vocational School", 18

2. Random files

Write data to a random file, using the put # statement. The syntax format is as follows:

Put [#] FileNum, [Recnum],usertype

Description

(1) FileNum is the file number to open; Recnum is the record number to write, and if omitted, the last record written in the previous record with the GET and put statements read and write, and if the get and put statements are not executed, start with the first record

(2) Usertype is a user-defined data type variable that contains the data to be written to. For example: We write data to the 5th record in the previous Student.txt file, which can be used:

Stud. No = 0301
Stud. Name = "Wang Wu"
Stud. Age =20
Put #1, 5,stud

If you want to insert more than one or two data, first determine the length of the file and each record so that you can calculate how many records are in the file. We can use the LOF () function to return the length of a file, and the Len () function returns the length of each record. The number of records in a calculated file can be divided by the length of the file to the length of the record. Examples are:

Nextrec= (Lof (1)/len (usertype)) +1

Put #1, Nextrec,usertype

3. binary files

The following is the format of the statement written to the file in binary mode and its description:

Format:

Put [#]filenumber, [Pos], Var

Function: A binary way, starting from the location specified in the file to write, the length of the given variable data

Description

(1) FileNumber is a file number that is opened in binary mode.

(2) POS is used to specify the byte position at which the write operation occurs, and, if omitted, the current file pointer position.

(3) var is a variable that holds the data that is written. The statement is automatically written to the file based on the length of bytes contained in the Var variable, and if Var is a variable-length string variable, the number of bytes transferred equals the current number of bytes in Var

Open method Read and write files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.