Hardware and software setup

Vb6 file system menu operation code examples. Reading and writing to a text file

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

This article will focus on 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.

There is a function in Visual Basic free file, 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 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 " Variable MyFile is assigned free channel and now it can be used to work with files

Working with text files

Most often it is necessary to meet with 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 a file for reading, if the file does not exist, then 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, 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, using the function Input(Number_of_read_characters, #file_number) and line by line, for this the function is used Line Input#file_number, Where_to read.

DimMyFile

Dim S As String "Variable to store 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

DimMyFile "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 to store the final data

MyFile = FreeFile "Assign a free channel to work with files

"Open file TEST.TXT for reading

For i = 1 to 5

Line Input #MyFile, tS "Read 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 to store read data

MyFile = FreeFile "Assign a free channel to work with files

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

S = Input$(LOG(1), 1) "Read 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.

Below the following code will create on drive C:\ new file TEST.TXT and write two strings into it, the first without quotes and the second with quotes:

DimMyFile "Declare a variable for a free file

MyFile = FreeFile "Assign a free channel to work with files

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

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

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

Close #MyFile "Close the file

That's actually all. As you probably already understood, the operator used to close a file is Close#file_number, wherein, # file_number not required to be specified.

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

8. STORING AND READING INFORMATION

So that after the program ends, all the data created in memory is not lost, you need to be able to save information on the hard disk. Otherwise, all information will disappear without a trace. Data can be stored and read in various 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 is reasonable to use databases.

8.1. Opening files with the "Open »

A file is a named area of ​​any external storage medium. Data "live" in the computer's memory, and files - 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, then 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, while the extension usually indicates the format of the file or what program it was created with.

Before you start working with a file, you must ask the operating system pointer (descriptor) file. To get it, use the " FreeFile". 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. 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 % is a variable that stores the file pointer;

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

· Open – operator name;

· FilePath - the full name of the file;

· For is 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

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 for working 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 - record;

· Read Write - reading and writing.

Note

Append and Output access modes only allow Write access, Input only Read access, and Binary and Random all three access types.

· LockType is an optional parameter that determines whether other programs can use this file while your program is working with it. Usually it is associated with networking (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

Write to file is blocked, but reading is allowed

Lock Read Write

Both reading and writing to it is 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 that must be followed by a parameter specifying 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 the file after you have finished 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 defined using the EOF (End Of File ) function:

EOF(FileHandle)

· EOF – function name;

· FileHandle is the file handle whose end is being determined.

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

8.2. Reading and writing to a text file

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

To write information, two statements are used "Print" and "Write", the syntax of which is as follows:

Print #FileHandle%, VarBuffer[;]

Write #FileHandle%, VarBuffer[;]

· Print /Write - operator keywords.

· #FileHandle % - file pointer to which the 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, the "Input" and "Line Input" operators are used. 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 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 data on the same line up to the first delimiter (for text data, the delimiter 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 control over 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 the mode " Binary". 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 of the file, this mode is also called − direct access mode. Another feature of this mode is the ability to simultaneously write and read information to 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 operator for writing information.

· RecNumber – byte number of the file to 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 statement:

Get #FileHandle%, , NameVar

· Get is the name of the information recording operator.

· FileHandle % - file pointer.

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

· NameVar - the name of the variable in 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 , whose code corresponds to the byte value. 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, 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

Graphic images can also be saved in files and retrieved from them. To extract a picture 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 is the name of the picture window control, image control, or form;

· LoadPicture - function name;

· FilePath is the full name of the file.

SavePicture ImageCtrl .Picture, FilePath

· SavePicture – operator name;

· ImageCtrl is 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 full name of the file, indicating its location on the disk.

8.5. Working with data in the registry

You can use the Windows Registry to store small pieces of character-format information. Visual Basic has four procedures that you can use to access it. They are very easy to use, but have one major drawback: data can only be accessed 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 " Win 32 API".

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

MyString = 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 (parameter missing).

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

SaveSetting VBKeyName, Section, Key, MyString

· SaveSetting is the name of the operator.

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

To get 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 is the name of the function.

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

To remove an entire parameter section, use an operator with the following syntax:

DeleteSetting VBKeyName, Section, Key

· DeleteSetting is the name of the operator.

Security questions for self-examination

  1. How can some information be stored long-term?
  2. What is a file?
  3. What filenames do you know?
  4. Give the syntax of the "Open " operator. Explain the purpose of its parameters.
  5. How can I organize the joint access of several applications to the same file at the same time?
  6. How to determine that the information in the file is exhausted?
  7. Why is it recommended to close the file after working with it?
  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" statements 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 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 to open and save files, select fonts and colors, and use the object clipboard for storing text fragments, using the example of creating a simple text editor.

Test questions:

1. What are the ways to open a text file? How to close text and any other open file?

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

3. How is data read from a text file opened for reading? What is the difference between the Input and Line Input operators? What function can be used to read a given number of characters from a file? How to read all characters of a file?

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

5. With what operators from the file raf records are read and into the file raf new records being written?

6. For what purpose is the index defined 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 the control can be applied CommonDialog to load the contents of a text file into a text field? How to use the same control to save the edited text in a text file?

9. How you can apply the control CommonDialog to download file content rtf in field Richtext box? How to use the same control to save the edited text to a file rtf?

10. How you can apply the control CommonDialog to change the values ​​of the font parameters and to change the color of the text in the window text box(or a selected piece of text in a window Richtext box)?

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 an identification number, full name, date of birth and place of birth of an employee. The rows form a table that will be imitated on the screen by 4 Combo Box controls (Fig. 7.1), which form an array of Comb(i) objects with the Style property set to 1 - SimpleCombo.

Highlight the line to be deleted", vbExclamation

Comb(j).RemoveItem i

‘Insert new record to table:

Private Sub mnuInsert_Click()

i% = Comb(0).ListIndex

If i< 0 Then

MsgBox "Select a 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 place of birth."), i

‘Changing an entry in a table:

Private Sub mnuUpdate_Click()

i% = Comb(0).ListIndex

If i< 0 Then

MsgBox "Select line to modify", vbExclamation

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

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

Comb(2).List(i) = InputBox("Enter date of birth", 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 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 block

‘ Writing table details 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.

Format file TXT will be loaded into the text field (left field in Fig. 7.2), and the format file RTF- in field Richtext box(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 the menu commands Font, color And Edit. Below is the procedure code also only for menu commands file (open, Save And SaveAs). Compiling 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

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

Exercise 1. In the process of completing the task, students master the possibilities of working with random access files available in VB 6 ( RAF-randomaccessfile).

For a given database table, a user-defined data type is declared, a variable of this type is declared (tutorial , pp. 108 - 112), procedures are compiled and debugged that use the user-defined 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 the 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 "Auto Service" database.

car

car

malfunctions

The bottom row 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 Car Service database.

malfunctions

Name

malfunctions

Price

The bottom row of table 7.2 shows the types of fields.

Using the example application 7.1 as a sample, arrange for 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 work of the menu commands shown in Fig. 7.1.

Task 2. As part of the activity, students add new features to the example application 2 that allow the application to be treated 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. Richtext box, as well as choosing the color of the symbols of the selected fragment and choosing 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 value of the Flags property to 1, 2, or 3 (see tutorial , p. 183).

Option 2. Using the Control CommonDialog implement menu commands Edit(submenu Copy, Cut And paste), whose purpose is copying or removal to the clipboard of the selected text fragment, as well as insert to the selected place of the clipboard content text.

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

clipboard. SetText RichTextBox1.SelText

RichTextBox1.SelText = Clipboard. gettext

Liked the article? Share with friends!
Was this article helpful?
Yes
Not
Thanks for your feedback!
Something went wrong and your vote was not counted.
Thanks. Your message has been sent
Did you find an error in the text?
Select it, click Ctrl+Enter and we'll fix it!