Vb6 file system menu code examples. Moving, copying and deleting files

8. SAVING AND READING INFORMATION

To ensure that all data created in memory is not lost after the program is completed, you need to be able to save information on your hard drive. Otherwise, all information will disappear without a trace. Data can be stored and read in a variety of ways. To work with information of various sizes and formats, you can use binary and text files. To store small amounts of information, you can use the Windows registry. And for the most complex tasks, it is wise to use databases.

8.1. Opening files using the operator "Open »

A file is a named area of ​​any external storage device. Data “live” in the computer’s memory, and files live on the hard drive. 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, it will be searched in the current folder, by default the folder where your application is located. The immediate 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 file format or what program it was created by.

Before you start working with the file, you must ask the operating system pointer (descriptor) file. To obtain it, use the “FreeFile” function. Then, using the “Open” operator, this pointer is associated with the required file. Only after this the program will 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% = FreeFile

‘ open the file

Open FilePath_

As [#]FileHandle%

...(working with a file)

Close [#]FileHandle

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

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

· Open – operator name;

· 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

Appending 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

Open 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 for working with simple records. If the file does not exist but will be created

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

· AccessType – description of the access type:

· Read – reading;

· Write – record;

· Read Write – reading and writing.

Note

With the Append and Output access modes, only the Write access type is available, with Input only Read, and with 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 with it. It is usually associated with working on the network (see Table 16).

Table 16

Possible values ​​for the LockType parameter

Meaning

Description

Shared

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

Lock Read

Reading of the file 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 to it are prohibited

· As is a keyword followed by a file pointer.

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

· Len is an optional keyword that must be followed by a parameter that specifies the length of the entry.

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

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

It is important to close a file when you are finished working with it. The "Close" statement frees the file pointer and the associated memory area.

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

EOF(FileHandle)

· EOF – function name;

· FileHandle is a pointer to the file whose end is being determined.

The function returns True if the end of the file is reached, otherwise 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 record 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 the information will be placed.

· VarBuffer – 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 % - pointer to the file from which information will be read.

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

The difference between the “Line Input” and “Input” operators 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 on one line up to the first delimiter (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

IN Visual Basic there are no means of controlling the format of previously created files. Therefore, the symbol "2" can be read as the corresponding number and vice versa.

8.3. Working with binary files

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

Put #FileHandle%, , NameVar

· Put – name of the information recording operator.

· RecNumber – the byte number of the file into which the information will be written (optional parameter).

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

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

Get #FileHandle%, , NameVar

· Get – the name of the information recording operator.

· FileHandle % - file handle.

· RecNumber – byte number of the file from which information will be read (optional parameter).

· 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 numeric value of the byte will be read, or a character of a fixed length of one character, then the byte will be read as a character, ANSI , the code of which corresponds to the byte size. This character can even be a control character, which cannot be achieved in the case of text files.

Note

In the absence of the “ RecNumber” parameter, writing or reading information will occur in the next byte of the file after the one with which it was previously worked.

8.4. Graphics manipulation

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

ImageCtrl.Picture = LoadPicture(FilePath)

· ImageCtrl – the name of an image window control, image control, or form;

· LoadPicture – function name;

· FilePath – full file name.

SavePicture ImageCtrl .Picture, FilePath

· SavePicture – operator name;

· ImageCtrl – the name of an image window control, image control, or form;

· Picture – 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

The Windows Registry can be used to store small pieces of information in character format. Visual Basic has four procedures that you can use to access it. They are very easy to use, but have one main drawback: you can only access data from a specific registry key: “MyComputer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings”. To access other sections of the registry, you need to use special functions “Win ​​32 API".

To get the value of a setting from the Visual Basic section of the Windows registry, you need to use the following function:

MyString = GetSetting(VBKeyName, Section, Key [,Default])

· MyString – a string to store the value returned by the function;

· GetSetting – function name.

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

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

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

To store a value in the Windows registry, use the following statement:

SaveSetting VBKeyName, Section, Key, MyString

· SaveSetting – operator name.

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

To obtain an array from the registry containing all parameter values ​​from a specific subkey, use the following function:

MyVariant = SetAllSettings(VBKeyName, Section)

· MyVariant is an array of values ​​of type “Variant” returned by the function.

· SetAllSettings – function name.

· Section – A string value representing a section or subsection of a particular application.

To remove an entire section of parameters, use a statement with the following syntax:

DeleteSetting VBKeyName, Section, Key

· DeleteSetting – operator name.

Test questions for self-test

  1. How can you store some information long-term?
  2. What is a file?
  3. What file names do you know?
  4. Give the syntax of the “Open” operator. Explain the purpose of its parameters.
  5. How can multiple applications share access to one file at the same time?
  6. How to determine that the information in a file is exhausted?
  7. Why is it recommended to close it after working with a file?
  8. What do you see as the difference between text and binary file modes?
  9. How is data read and written in text file mode?
  10. How is 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?

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

In this article we will talk about working with text files using Visual Basic.

File descriptor

To work with files operating system uses I/O channels, i.e. every open file has its own number.

In Visual Basic there is 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, an error occurs.

FreeFile[(RangeNumber) ]

RangeNumber-optional parameter that allows you to define the range of values ​​of free channels if RangeNumber= 0 (default), then the channel number is returned from the range 1 - 255, and if 1, then from the range 256 - 511.

MyFile = FreeFile "The MyFile variable is assigned free channel and now it can be used to work with files

Working with text files

Most often you encounter text files. Text files consist of the ASCII (American Standard Code for Information Interchange) character set.

Before you start writing/reading data, the file must be opened; this is done using the operator Open (File name) For As #File_number, Where:

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

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

Append- for adding, 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_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 = FreeFile

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

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

Dim MyFile "Declare a variable for a free file

Dim i As Integer "Variable for loop

Dim tS As String "Variable for reading strings

Dim S As String "Variable for storing final data

MyFile = FreeFile "Assigning a free channel for working with files

"Open the file TEST.TXT for reading

For i = 1 To 5

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

If i => 5 Then S = tS "If the fifth line, then 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 read data

MyFile = FreeFile "Assigning a free channel for working with files

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

S = Input$(LOG(1), 1) "Read the entire file into the 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 data in quotes, and Print without quotes.

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

Dim MyFile "Declare a variable for a free file

MyFile = FreeFile "Assigning a free channel for working with files

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

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

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

Close #MyFile "Close the file

That's all. As you probably already understood, the operator is used to close a file Close #File_number, wherein, # File_number it is not necessary to indicate.

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

Windows

Goal of the work: Learning and using VB 6 language operators to work with files various types: sequential (text) files, random access files, binary files. Research and use of the tool CommonDialog for opening and saving files, choosing font and color, and using the object Clipboard for storing text fragments, using the example of creating a simple text editor.

Control questions:

1. In what ways can you open a text file? How to close a text or any other open file?

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

3. How data is read from open for reading text file? How are the Input and Line Input operators different from each other? Which function can be used to read a specified number of characters from a file? How to read all characters of a file?

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

5. Using which operators from the file raf records are also read into the file raf Are new entries being written?

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

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

8. How to use the control CommonDialog to load the contents of a text file into a text field? How can I use the same control to save the edited text to a text file?

9. How to use the control CommonDialog to download file contents rtf in field RichTextbox? How to use the same control to save edited text to a file rtf?

10. How to use the control CommonDialog to change the font parameter values ​​and to change the text color in the window Textbox(or a selected piece of text in the window RichTextbox)?

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

Select the line to be deleted", vbExclamation

Comb(j).RemoveItem i

‘Insert new entry to the table:

Private Sub mnuInsert_Click()

i% = Comb(0).ListIndex

If i< 0 Then

MsgBox "Highlight the line to be inserted before it", vbExclamation

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

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

Comb(2).AddItem InputBox("Enter your birthday."), i

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

‘ Changing a table entry:

Private Sub mnuUpdate_Click()

i% = Comb(0).ListIndex

If i< 0 Then

MsgBox "Highlight mutable string", vbExclamation

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

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

Comb(2).List(i) = InputBox("Enter your birthday.", Comb(2).List(i))

Comb(3).List(i) = InputBox("Enter place of birth.", Comb(3).List(i))

‘ Clearing the entire table:

Private Sub mnuClear_Click()

‘ Filling a 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% = Comb(0).ListCount

Open "person. txt" For Output As #1

For i = 0 To N - 1

numb = Val(Comb(0).List(i))

fio = Comb(1).List(i)

bdate = CDate(Comb(2).List(i))

bloc = Comb(3).List(i)

Write #1, numb, fio, bdate, bloc

‘ Shutting down the application:

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.

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

object

Class

object

Property

object

Property value

“General panels

dialogue"

Open/Save As Tab

Font tab

Color tab

The table does not show the properties of menu commands Font, Color And Edit. Below is the procedure code also only for menu commands File (Open, Save And SaveAs). Composing code for other menu commands is the topic of the 2nd task of this work.

Private Sub mnuOpen_Click()

CommonDialog1.ShowOpen

F$ = CommonDialog1.FileName

If Right(F, 3) = "rtf" Then

RichTextBox1.LoadFile F

ElseIf Right(F, 3) = "txt" Then

Open F For Input As #1

S$ = Input(N, 1)

Private Sub mnuSave_Click()

CommonDialog1.ShowSave

F$ = CommonDialog1.FileName

Private Sub mnuSaveAs_Click()

CommonDialog1.ShowSave

F$ = CommonDialog1.FileName

RichTextBox1.SaveFile F, rtfRTF

During this work, the student must complete 2 tasks.

Exercise 1. In the process of completing the assignment, students master the capabilities available in VB 6 for working with random access files ( RAFrandomaccessfile).

For a given database table, a user data type is declared, a variable of this type is declared (tutorial, pp. 108–112), procedures that use a user type variable are compiled and debugged.

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 entry, Edit entry, Clear table.

Option 1.

Declare a custom data type for the “Car” table (Table 7.1) of the “Car Service” database.

car

car

malfunctions

The bottom line of Table 7.1 shows field types.

Option 2.

Declare a custom data type for the “Faults” table (Table 7.2) of the “Car Service” database.

malfunctions

Name

malfunctions

Price

The bottom line of Table 7.2 shows field types.

Using Example Application 7.1 as a template, organize the entry and editing of data for the table shown, writing that 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 menu commands shown in Fig. 7.1.

Task 2. During the assignment, students add new features to the example application 2 that allow the application to be viewed as a simple text editor.

Option 1 CommonDialog implement menu commands Font And Color(with submenu Character color And Background color). Using these commands, you should be able to select a font (its name, style and size) for the selected text fragment in the window RichTextbox, as well as selecting the color of the characters of the selected fragment and selecting the background color of the entire window.

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

Option 2. Using a 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 also insert to the selected text area of ​​the contents of the clipboard.

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

Clipboard. SetText RichTextBox1.SelText

RichTextBox1.SelText = Clipboard. GetText