Vb6 file system menu operation code examples. Creating a FileSystemObject

8. SAVING AND READING INFORMATION

So that after the program finishes all the data created in memory is not lost, you need to be able to save information on your hard disk. Otherwise, all information will disappear without a trace. You can save and read data in different ways. Binary and text files can be used to work with information of various sizes and formats. You can use the Windows registry to store small amounts of information. And for the most complex tasks, it makes sense to use databases.

8.1. Opening files using the operator "Open "

File is a named area of \u200b\u200bany external storage device. Data "live" in the computer memory, and files - on the hard disk. The program does not work with files directly, but uses the operating system as an intermediary.

There are two types of file names: full - in addition to the file name, the location of the file on external media is also indicated (for example, "C: \\ Program Files \\ Microsoft Visual Studio \\ VB98 \\ VB 6.EXE") and short - only the file name (VB 6.EXE ). If the file location is not specified, then it will be searched in the current folder, by default - the folder where your application is located. The direct file name consists of two parts: the actual unique file name and its extension. The name itself identifies the file, and the extension usually indicates the format of the file or what program it was created by.

Before starting to work with the file, you must ask the operating system pointer (descriptor) file... To get it, use the "FreeFile" function. Then, using the "Open" statement, this pointer is associated with the required file. Only then will the program be able to work with it. The syntax for opening a file is as follows:

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

FileHandle% \u003d FreeFile

'Open the file

Open FilePath _

As [#] FileHandle%

... (working with a file)

Close [#] FileHandle

· FileHandle% - a variable that stores the file pointer;

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

· Open - operator name;

· FilePath is the full name of the file;

· 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

Append 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. as a set of bytes. If the file does not exist but will be created

Input

Opening a file for reading in text format

Output

Opening a file to write a text file. In this case, all old information will be deleted. If the file does not exist but will be created

Random

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

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

· AccessType - description of the access type:

· Read - reading;

· Write - write;

· Read Write - read and write.

Note

For Append and Output access modes, only the Write access type is available, for Input, only Read, and for Binary and Random, all three access types are available.

· LockType is an optional parameter that determines whether other programs can use this file while your program is working on it. It is usually associated with networking (see Table 16).

Table 16

Possible values \u200b\u200bfor the LockType parameter

Value

Description

Shared

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

Lock Read

File reading is blocked, but writing is allowed

Lock write

Writing to the file is blocked, but reading is allowed

Lock Read Write

Both reading and writing are prohibited

· As is a keyword followed by a file pointer.

· # Is a character indicating that the value following it is a file pointer.

· Len is an optional keyword, followed by a parameter specifying the length of the record.

· CharInBuffer% - record length for the file opened in random access mode (Random).

· Close is the statement that closes the file associated with the specified handle.

It is important to close the file after you finish working with it. The "Close" statement releases the file pointer and its associated memory area.

When working with a 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 the file handle to specify the end of.

The function returns True if the end of the file has been reached; otherwise, it returns False.

8.2. Reading and writing to a text file

The text file is opened in the "Input", "Output" or "Append" access mode (see Table 15). The peculiarity of this mode is that it only works with specific printable characters. It is useless to work with service symbols.

To write information, use two operators "Print" and "Write", the syntax of which is as follows:

Print # FileHandle%, VarBuffer [;]

Write # FileHandle%, VarBuffer [;]

· Print / Write - operator keywords.

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

· VarBuffer is the value that will be written to the file.

· ; - an optional parameter used when writing to a text file, means that the next value will be written to the same line, and if it is absent, to the next one.

To read information from a file, use the "Input" and "Line Input" operators. The syntax is similar to each other:

Line Input # FileHandle%, VarBuffer

Input # FileHandle%, VarBuffer

· Line Input / Input - operator keywords.

· #FileHandle% - file pointer from which information will be read.

· VarBuffer is a variable into which information will be read.

The difference between the operators "Line Input" and "Input" is that the first is intended only for text files, and the second - for any. In the case of text files, “Input” reads the data in one line up to the first separator (for text data, the separator is “,” (comma), and for numeric data, “” (space) and “,”), and “Line Input »Reads the entire line at once, ignoring any delimiters.

Note

Visual Basic has no format controls for previously generated files. Therefore, the character "2" can be read as the corresponding number and vice versa.

8.3. Working with binary files

Files open in binary format by the "Open" operator in the "Binary" mode. A distinctive feature of this mode is that the work with the file is focused exclusively on specific bytes. Since Visual Basic can address directly to the desired location in the file, this mode is also called - direct access mode... Another feature of this mode is the ability to simultaneously write and read information in different parts of the file without reopening it. Writing to a file opened in binary mode is done using the following syntax:

Put # FileHandle%,, NameVar

· Put - the name of the information recording operator.

· RecNumber - byte number of the file to which information will be written (optional).

· NameVar is a variable whose contents will be written to a file.

Reading information from a file in binary mode is performed using the following operator:

Get # FileHandle%,, NameVar

· Get - the name of the information recording operator.

· FileHandle% - file pointer.

· RecNumber - file byte number from which information will be read (optional).

· NameVar - the name of the variable into which the read information will be placed.

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

Note

If the "RecNumber" parameter is absent, the information will be written or read in the next byte of the file after the one with which they worked before.

8.4. Graphics manipulation

You can also save and extract graphic images to files. To retrieve an icon from a bitmap or file and assign it to the Picture property of the PictureBox and Image controls, use the LoadPicture () function with the following syntax:

ImageCtrl.Picture \u003d LoadPicture (FilePath)

· ImageCtrl is the name of the picture window control, image control or form;

· LoadPicture is the name of the function;

· FilePath is the full name of the file.

SavePicture ImageCtrl .Picture, FilePath

· SavePicture - operator name;

· ImageCtrl - the name of the picture window control, image control or form;

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

· FilePath is the fully qualified file name and location on disk.

8.5. Working with data in the registry

You can use the Windows registry to store small chunks of character format information. There are four procedures in Visual Basic that you can use to access it. They are very easy to use, but they have one major drawback: you can only access data from a specific registry key: "MyComputer \\ HKEY _CURRENT _USER \\ Software \\ VB and VBA Program Settings". To access other registry keys, you need to use the special functions of the "Win 32 API".

To get the value of a parameter from a Visual Basic Windows registry key, use the following function:

MyString \u003d GetSetting (VBKeyName, Section, Key [, Default])

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

· GetSetting is the name of the function.

· VBKeyName is a string value that is the name of an internal VB / VBA subkey.

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

· Default is an optional argument, the value of which will be returned in case of an error (absence of a parameter).

The following statement is used to store some value in the Windows registry:

SaveSetting VBKeyName, Section, Key, MyString

· SaveSetting - operator name.

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

To get an array from the registry containing all parameter values \u200b\u200bfrom a specific subkey, use the following function:

MyVariant \u003d SetAllSettings (VBKeyName, Section)

· MyVariant is an array of "Variant" values \u200b\u200breturned by the function.

· SetAllSettings is the name of the function.

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

To delete an entire parameter section, use a statement with the following syntax:

DeleteSetting VBKeyName, Section, Key

· DeleteSetting - operator name.

Test questions for self-test

  1. How can some information be stored for a long time?
  2. What is a file?
  3. What file names do you know?
  4. Give the syntax for the "Open" statement. Explain the purpose of its parameters.
  5. How can multiple applications share the same file at the same time?
  6. How to determine that the information in the file has been exhausted?
  7. Why is it recommended to close it after working with a file?
  8. How do you see the difference between text and binary file modes?
  9. How is data read and written in text file mode?
  10. How are data read and written in 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 you work with graphic data?
  14. What are the basic principles of working with the Windows registry?
Windows

Objective: Learning and using the operators of the VB 6 language for working with files of various types: sequential (text) files, random access files, binary files. Researching and using the tool CommonDialog to open and save files, select a font and color, and use the object Clipboardfor storing fragments of text - using the example of creating a simple text editor.

Control questions:

1. In what ways can you open a text file? How do I close a text file and any other open file?

2. How is data written to a text file opened for writing? What is the difference between the Write and Print statements?

3. How is data read from an open-to-read text file? How do Input and Line Input statements differ from each other? What function can be used to read a given number of characters from a file? How can I read all characters in a file?

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

5.With which operators from the file raf records are read to file rafnew records are being written?

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

7. What are the specifics of using binary files? How do they open? How is reading from a binary file and writing to a binary file done?

8. How can the control be applied CommonDialog to load the content of a text file into a textbox? How can I save the edited text to a text file using the same control?

9. How the control can be applied CommonDialog to download file content rtf in field RichTextbox? How to save edited text to a file using the same control rtf?

10. How the control can be applied CommonDialog to change the values \u200b\u200bof the font parameters and to change the color of the text in the window Textbox (or a selected piece of text in a window RichTextbox)?

Example 7.1. Consider an application that demonstrates writing to a text file (and reading from a text file) "information about employees" - lines, each of which contains an identification number, full name, date of birth and place of birth of an employee. The rows form a table, which on the screen will simulate 4 Combo Box controls (Fig. 7.1), forming an array of Comb (i) objects, whose Style property is set to 1 - SimpleCombo.

Highlight the line to be deleted ", vbExclamation

Comb (j) .RemoveItem i

‘Insert new record into table:

Private Sub mnuInsert_Click ()

i% \u003d Comb (0) .ListIndex

If i< 0 Then

MsgBox "Select the line to insert before it", vbExclamation

Comb (0) .AddItem InputBox ("Enter number"), i

Comb (1) .AddItem InputBox ("Enter name"), i

Comb (2) .AddItem InputBox ("Enter date of birth."), I

Comb (3) .AddItem InputBox ("Enter the place of birth."), I

‘Change the entry in the table:

Private Sub mnuUpdate_Click ()

i% \u003d Comb (0) .ListIndex

If i< 0 Then

MsgBox "Highlight the line to be modified", vbExclamation

Comb (0) .List (i) \u003d InputBox ("Enter number", Comb (0) .List (i))

Comb (1) .List (i) \u003d InputBox ("Enter your name", Comb (1) .List (i))

Comb (2) .List (i) \u003d InputBox ("Enter your date of birth", Comb (2) .List (i))

Comb (3) .List (i) \u003d InputBox ("Enter birthplace", Comb (3) .List (i))

‘Clearing the entire table:

Private Sub mnuClear_Click ()

'Populating the table with 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

‘Writing table information to 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

‘Application shutdown:

Private Sub mnuExit_Click ()

Example 7.2 ... Consider an application that demonstrates the use of controls CommonDialog to open and save a file, to select a font and color, and to edit text.

Format file TXT will be loaded into the text box (left box in Figure 7.2), and the format file RTF - in field RichTextbox (right margin in Fig. 7.2).

object

Class

object

Property

object

Property value

“Panels of general

dialogue "

Open / Save As Tab

Font Tab

Color Tab

The table does not show the properties of the menu commands Font, Color and Edit... Below is the code of procedures also for menu commands only File (Open, Save and SaveAs). Writing code for other menu commands is the topic of the 2nd task 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 complete 2 tasks.

Exercise 1. In the process of completing the assignment, students master the capabilities of working with random access files ( RAF -randomaccessfile).

For a given database table, declare a custom data type, declare a variable of that type (tutorial, pp. 108 - 112), build and debug procedures that use a custom type variable.

In particular, procedures for menu commands are implemented Write to fileRAF and Read from fileRAF... As in example 7.1, an array of objects is used to edit data. ComboBox and menu Edit with five submenu commands: Add a note, Delete entry, Insert record, Change record, Clear table.

Option 1.

Declare a custom data type for the "Car" table (Table 7.1) of the "Autoservice" database.

car

car

malfunctions

The bottom line of Table 7.1 shows the types of fields.

Option 2.

Declare a custom data type for the "Faults" table (Table 7.2) of the "Autoservice" database.

malfunctions

Name

malfunctions

The cost

The bottom line of Table 7.2 contains field types.

Using the example application 7.1 as a sample, organize data entry and editing for the presented table, writing this data to a random access file, and reading data from a random access file. As in example 7.1, these actions are implemented as the operation of the menu commands shown in Fig. 7.1.

Task 2. In the course of the assignment, students supplement the application of Example 2 with new features that allow them to consider this application as a simple text editor.

Option 1 CommonDialog implement menu commands Font and Color (with submenu Character color and Background color). With the help of these commands, the choice of the font (its name, style and size) for the selected text fragment in the window should be provided RichTextbox, as well as the choice of the color of the symbols of the selection and the choice of the background color of this entire window.

Note: When setting up an object CommonDialog to select a font using the (Custom) property, be sure to set the Flags property value to 1, 2, or 3 (see the tutorial, p. 183).

Option 2... Using the control CommonDialog implement menu commands Edit (submenu Copy, Cut and Paste), the purpose of which is copying or deletion to the clipboard of the selected text fragment, and insert to the highlighted place in the text of the clipboard content.

Note: To clipboard (object Clipboard) you can use the SetText and GetText methods:

Clipboard. SetText RichTextBox1.SelText

RichTextBox1.SelText \u003d Clipboard. GetText

Every program must save data to disk and read it from disk. This is necessary, for example, to save the program settings, the user is unlikely to like the program, which will have to be configured again the next time it starts.

This article will focus on working with text files using Visual Basic.

File descriptor

The operating system uses input / output channels to work with files. each open file has its own number.

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

FreeFile [(RangeNumber) ]

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

MyFile \u003d FreeFile "The variable MyFile has been assigned a free channel and can now be used to work with files

Working with text files

Most often you come across text files. Text files are composed of the ASCII (American Standard Code for Information Interchange) character set.

Before starting to write / read data, the file must be opened, this is done using the operator Open (File name) For As #File_numberwhere:

Input - open the file for reading, if the file does not exist, then an error occurs;

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

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

Reading text files can be done in two ways: read character by character, for this use the function Input (Number of_Characters to Read, #File_number) and line by line, the function is used for this Line Input #File_number, Where_to_read.

Dim MyFile

Dim S As String "Variable for storing read data

MyFile \u003d FreeFile

Open ("C: \\ TEST.txt") For Input As #MyFile

Line Input #MyFile, S "Reading the first line from the TEST.TXT file into the S variable

Dim MyFile "Declare a variable for a free file

Dim i As Integer "Variable for the loop

Dim tS As String "Variable for reading lines

Dim S As String "Variable for storing final data

MyFile \u003d FreeFile "Assigning a free channel for working with files

"Opening the TEST.TXT file for reading

For i \u003d 1 To 5

Line Input #MyFile, tS "Reading the TEST.TXT file line by line

If i \u003d\u003e 5 Then S \u003d tS "If the fifth line, then we store it in the variable S

Next i

Close #MyFile "Close the file

Dim MyFile "Declare a variable for a free file

Dim S As String "Variable for storing the read data

MyFile \u003d FreeFile "Assigning a free channel for working with files

Open ("C: \\ TEST.txt") For Input As #MyFile "Opening the TEST.TXT file for reading

S \u003d Input $ (LOG (1), 1) "Reading the entire file into variable S

Close #MyFile "Close the file

There are operators for writing to a file Print #File_number, Data and Write #File_number, Data... The only difference between these operators is that Write writes the data in quotes, and Print without quotes.

The following code will create a new TEST.TXT file on the C: \\ drive and write two lines into it, the first without quotes and the second in quotes:

Dim MyFile "Declare a variable for a free file

MyFile \u003d FreeFile "Assigning a free channel for working with files

Open ("C: \\ TEST.txt") For Output As #MyFile "Open the TEST.TXT file for recording

Print #MyFile, "This string is written by the Print operator, it is without quotes ..."

Write #MyFile, "This line was written by the Write statement, it is in quotes ..."

Close #MyFile "Close the file

That's all. As you probably already understood, the operator is used to close the file Close #File_number, wherein, # File_number is optional.

The article is a bit crude, but it will be useful for novice programmers. Next time I'll talk about working with binaries.