Home Flowers Vb6 file system menu operation code examples. Adding data to the file. Reading File System Objects Files

Vb6 file system menu operation code examples. Adding data to the file. Reading File System Objects Files

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

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

File descriptor

To work with files, the operating system uses input / output channels, i.e. 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 ​​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 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_number, where:

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 = 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 "Declaring 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 = FreeFile "Assigning a free channel for working with files

"Open the TEST.TXT file for reading

For i = 1 To 5

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

If i => 5 Then S = 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 = FreeFile "Assigning a free channel for working with files

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

S = Input $ (LOG (1), 1) "We 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 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 "Declaring 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 TEST.TXT file for recording

Print #MyFile, "This string was 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 it is not necessary to specify.

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

Windows

Purpose of work: Learning and using the operators of the VB 6 language to work 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 Clipboard for 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 can 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 the 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 the characters in a file?

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

5.With which operators from the file raf the records are read to the file raf new records are 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 the control can 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 ​​of 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 has a value of 1 - SimpleCombo.

DIV_ADBLOCK265 ">

Comb (j) .ListIndex = i

‘Adding a new record to the table:

Private Sub mnuAdd_Click ()

XC (j) = Comb (j) .Text

Comb (j) .AddItem XC (j)

‘Deleting a record from a table:

Private Sub mnuRemove_Click ()

i% = Comb (0) .ListIndex

If i< 0 Then

MsgBox "Select the line to be deleted", vbExclamation

Comb (j) .RemoveItem i

‘Inserting a new record into a table:

Private Sub mnuInsert_Click ()

i% = 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, 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% = Comb (0) .ListIndex

If i< 0 Then

MsgBox "Highlight the line to be modified", 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 your date of birth", Comb (2) .List (i))

Comb (3) .List (i) = 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% = 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

‘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 field (left field in Fig. 7.2), and the format file RTF- in field RichTextbox(right margin in Fig. 7.2).

DIV_ADBLOCK267 ">

To implement the computer interface, the following table of properties is filled in:

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 only for menu commands 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 $ = 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 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, Edit entry, 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

Price

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. As they complete the assignment, students add new features to the application in Example 2, which make it possible to view the 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 the entire window.

Indication: 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 contents of the clipboard.

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

Clipboard. SetText RichTextBox1.SelText

RichTextBox1.SelText = Clipboard. Gettext

Character data

For each character in the computer memory, 1 byte (8 bits) of memory in ASCII encoding (or two bytes in Unicode) is allocated. Code tables contain 256 characters each. First code numbers 0 on 127 in any encoding are the same. From number 0 on 31 - control characters, number 32 Is a space. Further symbols: with 48 on 57 - numbers from 0 to 9 , with 65 on 90 - capital letters of the Latin alphabet, with 97 on 122 - small letters of the Latin alphabet. In between, there are signs. Table positions with 128 on 256 are used for national symbols of different languages.

Character data can be compared with each other using the same comparison operations as with arithmetic data. Comparison occurs character by character (byte) from left to right. In fact, the corresponding character codes are compared.

To process character data, you can use the operation of concatenation of operands (the sign of the operation is the symbol "+" or &).

A character string can always be converted to a one-dimensional array of individual characters by splitting it using the function MID or Split. After processing the array, its elements should be merged back into a string using the concatenation operation & (Concatenation).

Solving the vast majority of tasks requires mastering the built-in functions of VB6

Function

Actions performed

Example

Determines the length of the specified character variable in bytes (number of characters)

Fio = "Ivanov"

Cuts from a variable NS left k characters. The cut characters can be assigned to another variable

Fio = "Ivanov"

T = "Ivan"

Similar to the previous function, only on the right

Fio = "Ivanov"

Cuts out k characters from variable x starting from position pos inclusive

Fio = "Ivanov"

T = "vano"

NS to a decimal number.

Converts the specified character variable NS into an integer

Converts a number y to a character string. Taking into account the sign. If the number is positive, a space is substituted for the sign

s = "- 678 123.45"

Result - the character corresponding to the specified number in the character table

Outputting uppercase letters of the Latin alphabet

Specifies the numeric code of the first character in a string NS

Print ASC (”123”)

Print ASC (”1a2m”)

Print ASC (”ABC”)

On-screen 49 32 65

Starting from position n, defines the position of the first occurrence of the substring y in line x... If not, then the result is 0.

x = "corn"

Print INSTR (1, x, y);

Print INSTR (2, x, y);

On screen 1 3

Returns a copy of string x after removing whitespace characters from the left side of the string (leading spaces)

Returns a copy of string x after removing the space characters from the right side of the string (trailing spaces)

Returns a copy of string x after removing leading and trailing spaces

Returns a copy of string x with all uppercase characters converted to lowercase characters

Returns a copy of string x with all lowercase characters converted to uppercase characters

Changes the case of letters of a character string, depending on the value of the parameter P

P = 1, uppercase

P = 2, lowercase

P = 3, first capital letter only

Reverse the order in a line

Returns a string of spaces of length n characters

REPLASE (S, S1, S2, n, k)

Replaces the substring S1 in the string S with the substring S2, starting from position n, k - the number of substitutions, if not specified, then all occurrences of S1 are replaced.

print Replace (s1, ”1”, ””, 1)

On screen 23

Split function

New feature introduced in Visual Basic 6.0. The Split function is used to split a string into substrings using the substring separator. Returns a one-dimensional array with the Variant (String) data type containing the found substrings as elements.

Split (Expression ,,,)

Expression - Required argument - string to split. If the argument contains a null string (""), then an empty array is returned, i.e. array without elements and data.

Delimiter - Optional argument - type characters String which are used as line separators. If omitted, it defaults to a space character (""). If the argument contains a null string (""), then a singleton array containing the entire string is returned.

Limit - An optional argument containing the number of substrings to return. If the argument is omitted or equal to -1, then the entire line is processed.

Compare - An optional argument is a numeric constant that specifies the type of comparison.

Function Join

A function that performs the opposite action - concatenation of array elements into a string using the specified delimiter.

Join (name_array,)

Example ... Given text. Determine the number of offers. Find the number of words starting with the letter "p". On the form, in the Text1 field - the original text is located, in the Text2 field - the number of sentences, in the Text3 field - the number of words starting with the letter p.

Private Sub Command1_Click ()

s1 $ = "Hello Paul! Happy Holidays! Best wishes Peter."

a $ = Mid (s1, i, 1)

If (a = ".") Or (a = "?") Or (a = "!") Then kp = kp + 1

For i = 1 To ns - 2

If Mid (s1, i, 1) = "П" Or Mid (s1, i, 1) = "п" Then ks = ks + 1

If Mid (s1, i, 2) = "П" Or Mid (s1, i, 2) = "п" Then ks = ks + 1

Text2.Text = Str (kp)

Text3.Text = Str (ks)

Private Sub Command2_Click ()

OperatorMid

Syntax

Mid (stringvar, start [, length]) = string,

where stringvar is the name of the string variable to modify,

start- the position of the character in stringvar, from which the replaced part of the string begins,

length- the number of characters to replace,

string- string expression for replacement.

Mid (s1, 9) = "Gilles"

The number of characters to replace is always less than or equal to the number of characters in stringvar.

This operator should not be confused with the function of the same name!

Files

Depending on the organizational structures information in the file, storage method and access it is customary to distinguish three types of files for this information:

    Sequential access files ... As a rule, these are text files. The structural unit of such files is a string. The data in them is stored as a chain of ASCII codes and can be processed by any text editor. Writing and reading data when working with such files occurs strictly sequentially (you cannot access the second record without reading the first one).

    Random access files ... These are structured files that contain information in the form of records. For example, database files. The components (fields) in the records of such files can be of different types. But all records of sequential access files have constant length and sequence number. This allows you to immediately access the desired recording without sequentially viewing all the previous ones.

    Binary (binary) files ... These files can be sequential access files, but the information in them is presented in the form of bytes or blocks of bytes. These files include files with the .exe extension, i.e. software. These can be random access files: their record size is always 1 byte, and any byte can be read by its ordinal number.

New on the site

>

Most popular