the Internet Windows Android

VB6 Work Menu File System Examples Code.

Each program must save data to the disk and read them from the disk. This is necessary, for example, to save the program settings, it is unlikely that the user will like the program that the next time you have to configure again.

This article we will talk about working with text files by Visual Basic.

File handle

To work with files operating system Uses I / O channels, i.e. everyone open File It has its own number.

In Visual Basic there is a function Freefile.which returns a free channel number that can be used to work with the file. If there are no free channels, then an error occurs.

FREEFILE [(RangeNumber) ]

RangeNumber -Hellifying parameter that allows you to define the range of free channel values \u200b\u200bif RangeNumber \u003d 0 (default), then the channel number is returned from the range 1 - 255, and if 1, then from the range of 256 - 511.

MyFile \u003d Freefile. "The MYFILE variable is assigned a free channel and now it can be used to work with files

Working with text files

Most often you have to meet with text files. Text files consist of a set symbols ascii. (American Standard Code for Information Interchange. - American standard code For information sharing).

Before start writing / reading data, the file must be opened, it is done using the operator Open (File name) For as #File numberWhere:

Input - open a read file if the file does not exist, the error occurs;

Output. - for recording, if the file does not exist, it will be created, and if the file exists, it will be overwritten;

Append. - To add if the file does not exist, it will be created, and if the file exists, the data will be added to the end of the file.

Reading text files can be performed in two ways: read prevail, for this uses the function Input (Number_stile_Simvol, #File number) and line up for this function Line Input #File number, Whereby.

Dim MyFile.

Dim s AS String "Data storage variable

MyFile \u003d Freefile.

Open ("C: \\ Test.txt") for input as #myfile

Line Input #myFile, S "Read the first line from the Test.txt file to the variable s

Dim MyFile. "We declare a variable for a free file

Dim I AS Integer "Cycle variable

Dim TS AS String "Variable for reading strings

Dim s AS String "Variable for storing final data

MyFile \u003d Freefile. "We assign free channel to work with files

"Open the Test.txt file to read

For i \u003d 1 to 5

Line Input #myFile, TS "Read the Test.txt file line

If i \u003d\u003e 5 then s \u003d ts "If the fifth line, then remember it in the variable s

NEXT I.

Close #myFile "Close File

Dim MyFile "We declare a variable for a free file

Dim S AS String "Storage Variable Read Data

MyFile \u003d Freefile. "We assign free channel to work with files

Open ("C: \\ Test.txt") for input as #myfile "Open the Test.txt file to read

S \u003d Input $ (log (1), 1) "Read the entire file in the variable s

Close #myFile "Close File

Operators exist to write to the file Print #File number, Data and Write #File number, Data. Distinguishes these operators only that Write writes data in quotes, and Print without quotes.

The following code will create on a C: \\ disk new file. Test.txt and will record two lines in it, the first without quotes, and the second in quotes:

Dim MyFile. "We declare a variable for a free file

MyFile \u003d Freefile. "We assign free channel to work with files

Open ("C: \\ Test.txt") for output as #myfile "Open the Test.txt file to record

Print #myfile, "This line is recorded by the PRINT operator, it is without quotes ..."

Write #myFile, "This line is recorded by the Write operator, it is in quotes ..."

Close #myFile "Close File

That's all right. As you probably understood, the operator serves to close the file Close #File number, wherein, # File number Not necessarily.

The article is a bit damp, but for novice programmers will be useful. Next time I will talk about working with binary files.

8. Saving and reading information

To do after the program shutdown, all data created in memory is not gone, you need to be able to save information on the hard disk. Otherwise, all the information will disappear without a trace. Save data and read them in various ways. To work with information from various volume and format, you can use binary and text files. You can use the Windows registry to store small amounts of information. And for the most difficult tasks, it is reasonable to use databases.

8.1. Opening files using the operator "Open »

File is a named area of \u200b\u200bany external information drive. The data "live" in the computer's memory, and the files are on the hard disk. The program does not work with files directly, but uses the operating system as an intermediary.

File names There are two types: Full - in addition to the file name, the location of the file on the outer carrier is also specified (for example, "C: \\ Program Files \\ Microsoft Visual Studio \\ VB98 \\ VB 6.exe") and brief - only file name (VB 6.exe ). If the location of the file is not specified, it will be sought in the current folder, the default folder where your application is located. The direct file name consists of two parts: the actual unique file name and its expansion. The name identifies the file itself, and the extension usually indicates the file format or on which program it is created.

Before you start working with the file, you must request from the operating system. pointer (descriptor) file. To obtain it, use the "FreeFile" function. Then, using the Open statement, this pointer is associated with the required file. Only after that the program will be able to work with it. File opening syntax is as follows:

'Get a free file pointer and assign it to a variable

Filehandle% \u003d Freefile

'Open Bevel

Open FilePath _

AS [#] Filehandle%

... (workfile)

Close [#] Filehandle

· FileHandle% is a variable in which the file pointer is stored;

· FreeFile - the name of the function that returns the file pointer;

· Open - the name of the operator;

· FilePath - full file name;

· For - a keyword followed by a description of the file access mode;

· Mode - file access mode (see Table 15);

Table 15.

File access modes

Access modes

Description

Append.

Adding data to the end of an existing text file. If the file does not exist, it will be created

Binary.

Opening a file in binary mode, i.e. In the form of a set of bytes. If the file does not exist, but will be created

Input

Opening a read file in text format

Output.

Opening a file to record a text file. At the same time, all the old information will be deleted. If the file does not exist, but will be created

Random

Opening a file in arbitrary access mode. This mode is used to work with simple entries. If the file does not exist, but will be created

· Access - an optional keyword followed by a description of the type of access;

· AccesStype - Access Type Description:

· Read - reading;

· Write - recording;

· Read Write - reading and writing.

Note

When APPEND and OUTPUT access modes, only the WRITE access type is available at INPUT - only read, and with Binary and Random all three types of access are available.

· LockType is an optional parameter defining whether other programs will use this file while your program works with it. It is usually associated with the work on the network (see Table 16).

Table 16.

Possible values \u200b\u200bof the LockType parameter

Value

Description

Shared.

The file will have full access to all users with the necessary rights.

Lock Read.

Blocks reading a file, and the record is allowed

Lock Write.

Blocks record to a file, and reading is allowed

Lock Read Write.

Do not read and write to it

· AS - the keyword followed by the file pointer.

· # - symbol indicating that the value following it is a file pointer.

· LEN - an optional keyword, followed by a parameter that defines the recording length.

· CharinBuffer% - recording length for a file open in arbitrary access mode (RANDOM).

· Close is an operator that closes the file associated with the specified descriptor.

It is important to close the file after the end of working with it. The "Close" operator frees the file pointer and the associated memory area.

When working with the file, namely when reading from it, it is very important to determine the end of the file. It can be determined using the EOF (End of File) function:

EOF (Filehandle)

· Eof - function name;

· FileHandle is a file pointer, the end of which is determined.

The function returns True (Truth) if the end of the file is reached, otherwise False is returned.

8.2. Reading and writing to text file

The text file is open in the "Input", "Output" or "Append" access mode (see Table 15). The peculiarity of this regime is that it only works with specific printed symbols. With service symbols work is useless.

For information recording, two PRINT and WRITE operators are used, the syntax of which is as follows:

Print # Filehandle%, Varbuffer [;]

Write # Filehandle%, Varbuffer [;]

· Print / Write - keywords operators.

· #FileHandle% is the file pointer to which information will be placed.

· VarBuffer is a value that will be recorded in the file.

· ; - The optional parameter used when writing to the text file means that the next value will be recorded in the same line, and in the absence of it - to the next one.

To read information from the file, the "INPUT" and "LINE INPUT" operators are used. SyntaxichangchendrugDrugua:

Line Input # Filehandle%, Varbuffer

Input # Filehandle%, Varbuffer

· Line Input / Input - keywords operators.

· #FileHandle% is a file pointer from which the information will be believed.

· Varbuffer is a variable in which information will be read.

The difference between LINE INPUT and INPUT statements is that the first is intended only for text files, and the second is for any. In the case of text files, Input reads the data in one line to the first separator (for text data, the separator is "," (comma), and for numeric - "" (space) and ","), and "Line Input "Reads the whole line at once, ignoring any separators.

Note

Visual Basic does not control the format of the previously created files. Therefore, the symbol "2" can be read as an appropriate number and vice versa.

8.3. Working with binary files

Files open B. binary format Operator "Open" in "Binary" mode. A distinctive feature of this mode is that work with the file is focused exclusively on specific bytes. Since Visual Basic can add directly to the location of the file, this mode is also called - direct access mode. Another feature of this mode is the availability of simultaneous recording and reading information into different parts of the file without reapping it. Recording to a file that is open in binary mode is carried out by the following syntax:

Put # Filehandle%, NameVar

· PUT is the name of the information recording operator.

· RECNUMBER - the byte number of the file in which the information will be recorded (optional parameter).

· NameVar - variable, the contents of which will be recorded in the file.

Checking information from the file in binary mode is using the following operator:

Get # Filehandle%, NameVar

· Get - the name of the information recording operator.

· Filehandle% - file pointer.

· Recnumber - byte number of the file from which the information will be read (not required parameter).

· NameVar is the name of the variable in which read information will be placed.

Since the binary mode is focused on information bytes, then when reading from the file, the buffer variable must have a strictly defined type: either "byte", then the numeric value of the byte, or the symbol fixed length in one character, then the byte will be read as a symbol, ANSI whose code corresponds to the value of byte. This symbol may even be a manager, which cannot be achieved in the case of text files.

Note

In the absence of the "RecNumber" parameter, the recording or reading of information will occur in the following panel of the file after you have worked with.

8.4. Manipulation graphics

You can retain graphic images in files and extract. To remove from the raster file or the icon file and assign it to the "Picture" property of the "PictureBox" and "Image" control, use the "LoadPicture ()" function with the following syntax:

Imagectrl.picture \u003d LoadPicture (FilePath)

· Imagectrl - the name of the window control with a pattern, an image control element or form;

· LoadPicture - the name of the function;

· FilePath - full file name.

Savepicture Imagectrl .Picture, FilePath

· SavePicture is the name of the operator;

· Imagectrl - the name of the window control with a pattern, an image control element or form;

· Picture - the name of the object property responsible for the image;

· FilePath - the full name of the file indicating its location on the disk.

8.5. Working with data in the registry

To store small fragments of character format information, you can use the Windows registry. Visual Basic has four procedures that can be used to access it. They are very easy to use, but have one main disadvantage: you can access data only from a specific registry key: "MyComputer \\ HKEY _Current _user \\ Software \\ VB and VBA Program Settings". To access other registry sections, you need to use the special features of Win 32 API.

To get the value of the parameter from the Visual Basic section of the Windows Registry section, you need to use the following function:

MyString \u003d GetSetting (VBKEYNAME, SECTION, KEY [, DEFAULT])

· MyString is a string for storing the value returned by the function;

· GetSetting is the name of the function.

· VBKEYNAME - a string value that is the name of the internal subsection VB / VBA.

· Key - a string value that represents the name of the parameter in the section.

· Default is an optional argument whose value will be returned, in case of an error (no parameter).

To save some value in the Windows registry, the following operator is used:

Savesetting VBKEYNAME, Section, Key, My String

· Savesetting is the name of the operator.

· MyString is a string variable to which the value will be placed.

To obtain an array from the registry containing all the parameter values \u200b\u200bfrom a specific subsection, the following function is used:

MYVARIANT \u003d SETALLSETTINGS (VBKEYNAME, SECTION)

· MyVariant is a function returned by the range of values \u200b\u200bof the "Variant".

· SETALLSETTINGS - function name.

· Section - a string value representing a section or subsection of a specific application.

To delete a whole section of the parameters, an operator applies with the following syntax:

DELETESETTING VBKEYNAME, SECTION, KEY

· Deletesetting is the name of the operator.

Check questions for self-test

  1. How long can I store some information?
  2. What is the file?
  3. What file names do you know?
  4. Bring the Open operator syntax. Explain the purpose of its parameters.
  5. How can you organize joint access of multiple applications to one file at the same time?
  6. How to determine what information in the file is exhausted?
  7. Why after working with the file it is recommended to close?
  8. What do you see the difference of modes of text and binary files?
  9. How is the data read and write in the text file mode?
  10. How is the data read and write in the binary file mode?
  11. What is the difference between the "Print" and "Write" operators when working with files?
  12. What is the difference between the "INPUT" and "LINE INPUT" operators when working with files?
  13. How can I work with graphic data?
  14. What are the basic principles of working with the Windows registry?
Windows

Purpose of work: Learning and use of VB 6 operators to work with files different types: sequential (text) files, arbitrary access files, binary files. Research and use of the instrument COMMON.Dialog. To open and save files, select the font and color, as well as using the object Clipboard.to store text fragments - on the example of creating a simple text editor.

Control questions:

1. What ways can you open a text file? How to close text and any other open file?

2. How is the data in the text file open for writing? What is the difference between Write and Print operators?

3. How are the data from the text file open to read? What diffl from each other operators INPUT and LINE INPUT? With which function you can read from the file set number characters? How to read all file characters?

4. What is a user data type and how this concept is used when working with arbitrary access files ( raf.)?

5. With which operators from the file raf. Read records and file raf.will new records write?

6. For what purpose, the index is determined and use when working with the file raf.?

7. What are the features of using binary files? How do they open? How to read from binary file. and write to binary file?

8. How can I apply the control COMMON.Dialog. To download the contents of a text file in a text box? How to save the edited text in the text file using the same control element?

9. How can I apply the control COMMON.Dialog. To download the contents of the file rTF. in field RichTextBox.? How to save the edited text in the file using the same control element rTF.?

10. How can I apply an element COMMON.Dialog. To change the font parameters values \u200b\u200band to change the color of the text in the window TextBox. (or selected text fragment in the window RichTextBox.)?

Example 7.1. Consider an application demonstrating entry into a text file (and reading from a text file) "Employees information" - lines, each of which contains an identification number, full name, date of birth and the place of birth of an employee. The strings form a table that on the screen form will be mimic 4 of the COMBO Box control (Fig. 7.1), which generate the array of COMB objects (i), in which the Style property is 1 - SimpleCombo.

Highlight a remote string ", vbexclamation

COMB (j) .removeItem i

'Box new recording Table:

Private Sub Mnuinsert_Click ()

i% \u003d COMB (0) .listindex

IF I.< 0 Then

MSGBOX "Highlight a string to insert in front of it", vbexclamation

COMB (0) .ADDITEM INPUTBOX ("Enter the number"), I

COMB (1) .additem inputBox ("Enter FULL NAME"), I

COMB (2) .ADDITEM INPUTBOX ("Enter the date of the birth."), I

COMB (3) .additem inputBox ("Enter the place of birth."), I

'Changing the entry in the table:

Private Sub Mnuupdate_Click ()

i% \u003d COMB (0) .listindex

IF I.< 0 Then

MSGBOX "Highlight a variable string", vbexclamation

COMB (0) .list (i) \u003d InputBox ("Enter the number", COMB (0) .list (i))

COMB (1) .list (i) \u003d InputBox ("Enter FULL NAME", COMB (1) .List (I))

COMB (2) .list (i) \u003d InputBox ("Enter the date of the birth.", Comb (2) .list (i))

COMB (3) .list (i) \u003d InputBox ("Enter the place.", Comb (3) .list (i))

'Clearing the entire table:

Private Sub MnuClear_Click ()

'Filling the table information from a text file:

Private Sub Mnuload_Click ()

Open "Person. TXT" FOR INPUT AS # 1

INPUT # 1, Numb, Fio, BDATE, BLOC

COMB (0) .additem numb

COMB (1) .additem fio

COMB (2) .additem BDATE

COMB (3) .additem Bloc

'Recording table information in a text file:

Private Sub Mnusave_Click ()

N% \u003d COMB (0) .listcount

Open "Person. TXT" FOR OUTPUT AS # 1

For i \u003d 0 to n - 1

numb \u003d Val (COMB (0) .list (i))

fIO \u003d COMB (1) .List (I)

bDATE \u003d CDATE (COMB (2) .List (I))

bLOC \u003d COMB (3) .List (I)

Write # 1, Numb, Fio, BDATE, BLOC

'Shutdown of application:

Private Sub Mnuexit_Click ()

Example 7.2. . Consider an application that demonstrates the use of controls COMMON.Dialog. To open and save the file, to select font and colors, as well as to edit text.

Format file. TXT. will be loaded into the text field (left field in Fig. 7.2), and the format file RTF. - in field RichTextBox. (Right field in Fig. 7.2).

object

Class

object

Property

object

Value property

"General panels

dialogue

Open / Save AS tab

Bookmark Font.

Bookmark Color.

The table does not prevent the menu command properties. Font, Color and Edit.. Below is the procedure code only for menu commands. File (Open., Save. and Save.As). Drawing up code for other menu commands - the topic of the 2nd job of this work.

Private Sub Mnuopen_Click ()

COMMONDIALOG1.SHOWOPEN.

F $ \u003d Commondialog1.FileName

If Right (F, 3) \u003d "RTF" THEN

RichTextBox1.Loadfile F.

ELSEIF Right (F, 3) \u003d "TXT" THEN

Open F for Input AS # 1

S $ \u003d Input (N, 1)

Private Sub Mnusave_Click ()

Commondialog1.showsave

F $ \u003d Commondialog1.FileName

Private Sub Mnusaveas_Click ()

Commondialog1.showsave

F $ \u003d Commondialog1.FileName

RichTextBox1.Savefile F, RTFRTF

In the course of this work, the student must fulfill 2 tasks.

Exercise 1. In the process of completing the task, students are mastering available in VB 6 capabilities with arbitrary access files ( Raf -randomaccessfile).

For a given database table, a user data type is declared, a variable is declared this type (tutorial, page 108 - 112), and procedures in which the user-type variable is used.

In particular, procedures are implemented for menu commands. Write to fileRaf. and Read from file.Raf.. As in Example 7.1, an array of objects is used to edit data. Combo.Box. and menu Edit. With five commands submenu: Add a note, Delete recording, Insert writing, Edit Recording, Clear Table.

Option 1.

Announce a user data type for the "car" table (Table 7.1) Database "Auto service".

car

car

fault

At the bottom line of the table 7.1 - the types of fields.

Option 2..

Announce a user data type for the "Fault" table (Table 7.2) of the "Auto service" database.

fault

Name

fault

Cost

At the bottom line of the table 7.2 - the types of fields.

Using the application of Example 7.1 as a sample, to organize input and editing data for the table represented, record this data into a random access file and reading data from an arbitrary access file. As in Example 7.1, the specified actions implement how the operation of the menu commands shown in Fig. 7.1.

Task 2. During the task, students complement the application of Example 2 with new features that allow you to consider this application as a simple text editor.

Option 1 COMMON.Dialog. Implement menu commands Font and Color (with submenu Color symbols and Background color). Using these commands, a font selection (its name, drawing and size) should be provided for the selected text fragment in the window. RichTextBox.As well as selection of the color of the characters of the selected fragment and select the background color of the entire window.

Note: When setting up the object COMMON.Dialog. To select a font using the Properties (Custom), you must set the value of the flags property of 1, 2 or 3 (see the manual, page 183).

Option 2.. Using the control COMMON.Dialog. Implement menu commands Edit. (Submenu Copy, Cut. and Paste.), whose appointment is copy or removal In the clipboard of the selected fragment of the text, as well as insert In the selected place text of the contents of the clipboard.

Note: To the exchange buffer (object Clipboard.) You can use SETTEXT and GetText methods:

Clipboard. SetText RichTextBox1.selText.

RichTextBox1.selText \u003d Clipboard. GetText