Delphi writing to file. Recording to a text file, Excel, etc.

This article is aimed at beginners who want to learn how to work with files in Delphi. The article discusses standard I/O operations with files, typical mistakes and methods for their prevention.

In Delphi, a file is represented as a named data structure, i.e. sequence of the same type of data. Roughly speaking, this is a huge array, the number of elements of which is practically unlimited. To make it easier to work with files in Delphi, each separate file represents a file variable. Since it is a variable, it must be declared as a variable. However, first things first.

Step 1 - Declaring a File Variable

File variable in general view declared in the var section something like this:

F: file of Type;

For example:

F: File of integer;

It should be noted that text files are declared slightly differently:

And in general, text files are “special”. Some functions only work with text files. You can also declare not only an integer file, a text file, or a file of some other type, but also a file of your own type or record by placing the type or record declaration above the file variable declaration. For example:

TDay = (MON, TUE, WED, THU, FRI, SAT, SUN);

F: File of TDay;

F: File of TDay;

Please note that the length of the string fields in the record must be clearly defined (Name: String)

Step 2 - Assigning and Opening a File

After declaring a file variable, you need to associate it with a physical file on disk. This can be done using the AssignFile procedure:

AssignFile(var F: File; FileName: String);

For example:

var F: TextFile;

AssignFile(F, "text.txt");

After completing the procedure, the file variable F will be associated with the text.txt file located in the program folder. And all actions performed with the variable will act on this file. However, the variable can be freed for further use with another file using the CloseFile procedure, but more on that below. Now you need to open the file, in one of several ways, depending on your needs. You can create a new one or overwrite an existing one using the Rewrite(F) procedure. You can open for writing at the end of the file using the Append(F) procedure. And opening the file for reading is carried out by the Reset procedure.

Step 3 - Standard I/O operations with files

I/O are input/output operations. Here we will look at writing data to a file and reading that data. Recording first. You can write a variable or constant to a file of the type that the file was declared. For example, if a file was declared like this F: File of Integer, then only data of type Integer can be written to it. If you try to write data of a different type, the compiler will generate an error message. Writing to a file is carried out by the procedures Write(; P1; [...,Pn]) and WriteLn(; P1; [...,Pn]). The second differs from the first in that after writing the parameter, it moves the carriage to a new line, i.e. next parameter sign up for new line. Here is an example of using procedures:

var F: TextFile;

Str:= "Some Text";

WriteLn(F, Str);

Write(F, "this will be on the new stock");

write(F, "and this is on the same line");

Data is read using the procedures Read(; V1; [...,Vn]) and ReadLn(; V1; [...,Vn]). They differ in that after the parameter is read by the ReadLn procedure, the carriage moves to a new line, even if there was still data. Here's an example:

var F: TextFile;

ReadLn(F, Str2);//str2 will contain the data coming after str

Read(F, Str3);//str3 will contain the data that is on the new line after str2

I think it's not all that complicated.

Step 4 - Closing the file

The file variable must be freed after use, otherwise the program will not close and will generate an error. Also, freeing a file variable will be useful when you need to work with several files sequentially, and after working with the first file, you can free the variable and associate it with a new file. The procedure CloseFile(F: File) releases the file variable. I think there is no need for an example, because... she has no special features.

I think it will still be difficult for a beginner to understand how to work with files without examples. So let's take a look simplest example a program that, at the click of a button, will prompt the user for a file name and record the contents of TMemo. And when you press another button, the program will again request the file name, read the recorded data from there and place it in TMemo. I know that writing and reading in TMemo can be organized using special methods. But this is just an example for the article. In general, throw one TMemo and two buttons on the form. Change the first button handler to this form:

procedure TForm1.Button1Click(Sender: TObject);

FileName: String;

AssignFile(F, FileName);

for i:= 0 to Memo1.Lines.Count do

WriteLn(F, Memo1.Lines[i]);

This button will save a text file. So, in the var section I declared three local variables: F of type TextFile is a file variable for text files; FileName of type String will serve to store the file name; And i is of type Integer - for loops. In the first line I ask the user for the file name. In the second, I associate a file variable with a physical file on disk. The line Rewrite(F) creates new file or overwrites an existing one. So that the data is not replaced but added to the end of the file, this line must be replaced with Append(F). Next comes a loop from 0 to the number of all lines of Memo1. In the loop, the contents of all Memo1 lines are written in order to a file. Note that I'm using WriteLn to write a new line. If I used Write, then all the Memo1 lines in the file would turn into one.

The second button handler should look something like this:

procedure TForm1.Button2Click(Sender: TObject);

FileName, tmp: String;

FileName:= InputBox("File name", "Enter file name", "default.txt");

AssignFile(F, FileName);

while not EOF(f) do

Memo1.Lines.Add(tmp);

The assignment of local variables in this procedure is similar to the previous ones. The first and second lines are similar to the lines from the first button handler. Reset(F) - I open the file for reading using the Reset procedure. Next, a loop is launched over the entire file (while not EOF(F) do). The EOF(F: File) function returns true when the end of the file is reached. The loop reads one line from the file into the tmp variable and adds it to Memo1. That's all, I think it's quite simple. However, it is easy to trick the program into causing an exception. For example, when reading a file, the user can specify the name Not existing file. Then an error will occur. Next we will talk about ways to protect a program from exceptions

Method 1 - The simplest

Of course the simplest, but enough effective method protections can be organized using nested try - except and try - finally blocks. You know that if an exception occurs when executing a statement in the body of a try - except block, then execution further instructions stops and executes what is between except - end. But if an exception occurs, and then CloseFile(F) is found, then this procedure is not executed and the program will not be able to work correctly and terminate. The solution to this problem is to use nested try - except and try - finally. Here's an example

MessageDlg("Error working with file", mtError, , 0);

But this method may not work if there was an attempt to open a non-existent file (an exception will occur when executing CloseFile(F)).

Method 2 - Effective

It is known that the program itself takes care of exception handling. But she doesn't always do it right. That's why the best solution It would be nice to control the moment the file is opened. To do this, you must first disable automatic exception handling with the (I-) directive. And you can turn it on like this: (I+). Then check the value of the IOResult function. If the file is successfully opened, it returns 0. Here is an example:

if IOResult<>0 then

MessageDlg("File "+PChar(FileName)+ " does not exist", mtError, , 0);

EXIT; //can't continue

Insert all this into the file reading procedure (in the example above) instead of the Reset(F) line. You can also insure against failures by inserting this construction into the file saving procedure instead of the Rewrite line.

Named memory area on external media(disk) is called file. Any file has Name. Information, which is stored in a file, represents a set of elements of the same type. Size a file is usually limited only by the capacity of the device on which it is stored, which makes it possible to process large amounts of information.

Announcement method file depends on its type. There are three types of files:

text;

typed;

untyped.

Text file, consists of a sequence of any characters. The characters form lines, each of which ends with an end-of-line character. The end of the file itself is indicated by the "end of file" symbol. When writing information to a text file, all data is converted to a character type and stored in this form. You can view a text file using any text editor.

Description of the text file:

var variable_name: TextFile;

Typed file consists of elements of the same type, the number of which is not predetermined and can be any. It also ends with the "end of file" symbol. Data in a typed file is stored in binary codes and are not viewed text editors. The declaration of such files looks like:

variable_name: file of type;

IN untyped files information is read and written in the form blocks certain size, they can store data of any type and structure. Description of the untyped file:

var variable_name: file;

For file access use a special file variable.

For example:

c:file of integer;

For communications file variable with a file on disk, use the procedure:

AssignFile(variable, filename);

here variable is the name of a variable of any file type, file_name is a character string containing full name file (if the path to the file is not specified, it is assumed that it is in current directory).

For example:

S:=’text.txt’;

assign(f,’d:\tp\tmp\abc.dat’);

For opening an existing file use the procedure:

Reset(file_variable);

After opening a file, its first component is available.

To create a new file or delete information from an existing one, use the following procedure:

Rewrite(file_variable);

After execution various operations the file should be closed. To do this, use the procedure

CloseFile(file_variable);

Data recording to a text file is carried out by procedures

Write(variable, expression_list);

Writeln(variable, expression_list);

where expression_list are expressions of character, integer, real, string or logical types that will be written to the file associated with the file variable.

The Writeln procedure adds a line terminator at the end of each line.

EXAMPLE. A subroutine that creates on disk D file abc.txt and writes the multiplication table into it.

var f:TextFile; i,j:byte;

assignFile(f,"d:\abc.txt");

for i:=2 to 9 do

for j:= 2 to 9 do

write(f,i,"*",j,"=",i*j," ");

Reading data from the file is carried out sequentially from the beginning of the file by the procedure

Readln(variable, variable_list);

here the variables_list lists the variables into which the data read from the file associated with the file variable will be written.

The Readln procedure, after reading the next element from the file, moves to the next line.

Calling the following subroutine will result in the text from the file appearing on the form in the editing window D:\abc.txt:

procedure TForm1.Button1Click(Sender: TObject);

a:string; i:integer;

AssignFile(f1,"D:\abc.txt");

for i:=1 to 8 do

Memo1.Lines.Add(a);

Also applicable for typed files reading procedures And records

Read(variable, list of variables);

Write(variable, expression_list);

only the write and read expression types must match the declared file type. The Writeln and Readln procedures do not apply to typed files.

For moving through a typed file use the procedure:

Seek(variable, number);

This procedure allows you to navigate to an element with specified number, that is, it carries out direct access to file components. With direct access, file components are numbered from 0 to n-1, where n is the number of components in the file.

Ditto for direct access You can apply the following functions to the components of a typed file:

filesize(variable) – returns the number of real components in open file associated with file_variable (for empty file the function will return 0);

filepos(variable) – returns the value of the current position in the open file associated with the file variable (if the file has just been opened, the function will return zero; after reading the last component from the file, the function value matches the filesize value, indicating that the end of the file has been reached).

The Seek procedure and the filesize and filepos functions do not work with text files. The following routines work with both typed and text files:

Rename(variable, filename)

renames the closed file associated with the file variable according to the name specified in the file name line;

Erase(variable) – deletes closed file, associated with a file variable;

Eof(variable) evaluates to true if the end of the file associated with file_variable is reached, false otherwise;

EXAMPLE. The subroutine below works like this. Opens a real file d:\abc.dat and is written into it a certain amount of real numbers calculated using the formula. It is not possible to view the created file, since the information in it is presented in binary codes.

procedure TForm1.Button1Click(Sender: TObject);

AssignFile(f,"d:\abc.dat");

n:=StrToInt(Edit1.Text);

for i:=1 to n do

a:= sqr(i)/sqrt(i);

To ensure that writing to the file d:\abc.dat happened successfully, let's display its values ​​in the editing window:

procedure TForm1.Button1Click(Sender: TObject);

f1:file of real;

AssignFile(f1,"D:\abc.dat");

while not eof (f1) do

Memo1.Lines.Add(FloatToStr(a));

TASK. On disk E there is a file of integers abc.int, swap its maximum and minimum elements.

The following program works like this. The components of the file are read into an array. The array elements are displayed in the Memo1 field. Then the minimum and maximum elements of the array and their indices are searched. The maximum and minimum components are rewritten to the file at the corresponding positions.

Finally, the elements of the converted file are displayed in the Memo2 field.

procedure TForm1.Button1Click(Sender: TObject);

f:file of integer;

a:array of integer;

i,nmax,nmin:byte; max,min:integer;

AssignFile(f,"e:\abc.int");

for i:=0 to filesize(f)-1 do

Memo1.Lines.Add(FloatToStr(a[i]));

max:=a; nmax:=0;

min:=a; nmin:=0;

for i:=1 to filesize(f)-1 do

if a[i]>max then

if a[i]

for i:=0 to filesize(f)-1 do

Memo2.Lines.Add(FloatToStr(a[i]));

We will look in detail at how to copy, delete, and rename files. Let's learn how to read and write information into typed files.

Copying files using .

To do this, we need to call just one function, which specifically copies files. This is the CopyFile() function. It has three parameters, two of which are required. Here's the full syntax.
CopyFile("path to the initial file", "Path to where to copy", Overwrite or not)

Example: CopyFile("D:sekretBD.txt","C: ame.txt", true);

In the first parameter you can specify not only the full path to the file. If we specify, for example, the path “sekretBD.txt”, then our program will look for this file in its directory. The name and permission must be specified exactly as they are for the file, otherwise the program simply will not find the file.
In the second parameter you can also specify a relative path and there you can specify the file name and extension as you want. Those. Using this function you can do renaming too.
The third parameter is responsible for overwriting the file. If we specify true, then the file will not be overwritten, and if false, then the program will overwrite the file.

Renaming files using

The RenameFile() function is responsible for renaming files. It has 2 parameters. Here is its full syntax
RenameFile("path to file","new name");
To be honest, I'm not particularly happy with the syntax of this function. In it, you also need to specify the full path in both parameters. Those. if we, for example, write like this

RenameFile("C:2.txt","3.txt");

Then it will copy the file to the program directory. Those. It turns out that it can serve as a copy too. It's a bit strange.

Deleting files using

Well, everything is quite simple here. The function that can be used to delete a file is called like this:

DeleteFile("C:myprofile.txt");

The only thing is that it does not always delete the file 100%. When the file is protected, she will not be able to delete it.

Working with typed files in

What is a typed file? This is a file with a specific structure. Typically this structure consists of records and base types. In general, it is important that the type has a known fixed size, so you cannot use the string type, you need to do it like this: String[N].
First we need to declare a variable where the data from the file will be stored. This is done like this:

Var f: file of<Тип>
For example, f: file of string;

Then we need to connect to the file. There is an AssignFile command for this. To call, you need to specify two parameters, this is the variable that we declared above and the path to the file. For example

AssignFile(f,"C:delphi.ini");

Now the file needs to be opened. It can be opened in two ways: with or without re-grinding. The Rewrite method opens a file after first creating it. Those. if the file is not located in the path we specify, it will create it. If there was already such a file, it will be deleted and a clean file will be created again. The Reset method opens the file and places the pointer at the very beginning of the file. But this method is dangerous because if the file specified in the connection does not exist, the program will crash with an error. So to use the Reset function correctly, you need to tell the compiler to disable errors. This is specified by the directive ($I-) i.e. The full syntax for the reset function would be:

($I-)
Reset(f);
($I+)

After this, you need to check whether the file was opened or not. This can be done using the IOResult function. If it is not zero, then everything is successful.
Full syntax:

($I-)
Reset(f);
($I+)
If IOresult<>0 then<ваш код>

The FileExists function will also help you check. It needs to indicate the path to the file.
To read a file, use the Read() function, which specifies two parameters: the file variable and the record type, in our case it is string. Syntax:

To write to a file, use the Write() function, which specifies the same two parameters: the file variable and the record type, in our case it is string. Syntax:

While not eof(f) do
Read(f,String);

There is also a seek function, with which we can go to the record we are interested in. For example, we need to access record 20 and we do this:

There is also a truncate function, with which we can delete all entries in a file, starting from the pointer position. The position can be specified using the seek function, for those who do not understand.

After completing all operations with the file, you need to close it using the CloseFile(f) function;
That's all. This concludes the lesson. See you on the site!

Create a new Delphi project. First of all, we will develop the program interface. Let's change some properties of the main form. First of all, assign the appropriate value to the Caption property (form title) - for example, Working with files. Since our program window should always be on top of all other windows, we should set the FormStyle property to fsStayOnTop. We will not change any further properties of the form.

Place two category Label components in the upper left corner of the form, one above the other. Standard. For the top label, set the Caption property to What:, and for the second to Where:. Next to the labels, place one Edit component (input field) of the category Standard. Set the Name property of the top field to from and the Name property of the bottom field to where. Set the from.Text and where.Text properties to default paths, for example: c:\1.txt and d:\2.txt.

In order not to bother the user with copying or manually entering file paths, we will use standard dialog boxes for opening and saving files. The file open dialog box corresponds to the OpenDialog category component Dialogs, and the save dialog box - the SaveDialog component of the same category. Let's place these components on the form. For convenience, let's change the value of the OpenDialog1.Name property to Open1, and the value of the SaveDialog1.Name property to Save1.

To the right of the from and where fields we will place buttons for calling up the overview dialog box (Button category components Standard). Set the Caption property of these buttons to Review or simply add dots. If desired, you can change the size of the buttons.

Place the category Label component on the form under the where field Standard and set its Caption property to File Size:. To the right of this label, place another Label component, clearing its Caption property - this label will display the size of the file being processed.

Below we will place two buttons (Button components), assign their Caption properties the values ​​Copy and Cut. Below these buttons we will place components that will be used to select and delete files: the Edit component for entering the path to the file, a button for opening the browse dialog box, and a button for deleting the file.

Let's set the Edit1.Name property to Del, and the Text property to the default path. button Review place it on the right, and the button Delete a file- under the Del field.

The resulting shape should correspond to Fig. 2.1.

Rice. 2.1. Form Working with files

Program code development

Let's develop a procedure for copying a file. This could be implemented using WinAPI, but in this case the procedure, although it would be less cumbersome, would be “tied” to the system, which is undesirable for programs, so it is better to use Delphi libraries.

First, let's declare our procedure (let's call it doit) as a private member of the form class:

We will create the implementation of the procedure in the implementation section:

procedure TForm1.doit();
f1, f2: file of Byte;//Work with the first and second files
sor: Byte;//For byte-by-byte copying
sizez:LongInt;//Stores the file size
($I-)//Disable the directive that tracks errors
try//Start of exception handling block
//Associate the file variable f1 with the first file
AssignFile(f1, from.Text);
//Associate the file variable f2 with the second file
AssignFile(f2, where.Text);
Reset(f1); //Open the first file for reading
sizez:= Trunc(FileSize(f1)); //Determine the file size
//Display file size for user
Label4.Caption:= IntToStr(sizez div 1024) + "KB";
begin//Until the end of the first file is reached
//Read one byte from the first file
BlockRead(fl, cop, 1);
//Write one byte to the second file
BlockWrite(f2, cop, 1);
CloseFile(f1); //Close the first file
CloseFile(f2); //Close the second file
end;//End of exception handling block
if IOResult<> 0 //If an I/O error occurs
then MessageDlg("Error copying file!", mtError, ,0)//error message
(If there were no errors, then we display a window indicating the successful completion of copying)
ShowMessage("Copied successfully!");

⇘ Various constructs of the Object Pascal language (comments, branching operators, exception handling, etc.) are discussed in Appendix D.

This procedure will be used when copying and transferring files. We first open the files that the user has selected and then check to see if there were any errors when opening them. If there were no errors, then we display the size of the source file to the user and begin reading bytes from the first file, writing them to the second. If copying is completed and no errors occurred, a message indicating the successful completion of copying is displayed.

The doit procedure is called when the button is clicked Copy:

procedure TForm1.Button1Click(Sender: TObject);

At the click of a button Cut Normal copying should occur followed by deleting the copied file:

doit;//copy
DeleteFile(from.Text); //delete the source file

Now let's create procedures for selecting and saving a file using standard dialog boxes. To select the first (source) file, create the following OnClick event handler (the Button2 button corresponds to the from field):

then from.Text:= Open1.FileName

When the button is pressed Review The file selection dialog box opens (Open1.Execute). If the user clicked the button in this window Cancel(Open1.Execute = False), then we inform him about this and do not perform any actions. If the user has selected a file, then copy the path to it into the corresponding input field.

Let's create a similar event handler for selecting the destination path when copying the first file (the Button3 button corresponds to the where field):

then where.Text:= Save1.FileName
else ShowMessage("You have not selected a location to save the file!");

The same check is performed here as in the previous case. The selected path is then entered into the corresponding input field so that it can be adjusted if desired.

Now let's create a similar OnClick event handler for the button Review, used to select the location of the file to be deleted:

then Del.Text:= Open1.FileName
else ShowMessage("The file was not opened!");

The button itself Delete executes the following code when clicked:

procedure TForm1.Button6Click(Sender: tobject);
DeleteFile(Del.Text);//delete the file
if not FileExists(Del.Text)//check the existence of the file
then ShowMessage("File deleted!");//display a message

We first delete the file and then check if it exists on disk after performing the delete operation. If it does not exist, then we display a message indicating that the file was successfully deleted. Now you can compile and run the program. Window appearance Working with files shown in action in Fig. 2.2.

Rice. 2.2. File Working program in action

Full module source code

The complete code of the program module Working with Files is presented in Listing 2.1.

Listing 2.1. Program module Working with files
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ShellAPI, Gauges;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure doit; //declaration of procedure doit


f1, f2: file of byte; //work with the first and second files
litter: byte; //for byte-by-byte copying
sizez: longint; //stores file size
(I-) (disable the directive that monitors I/O errors)
//associate the File variable f1 with the first file
//bind the file variable f2 to the second file
Reset(f1); //open the first file for reading
sizez:= Trunc(FileSize(f1)); //find out the file size
//Display the file size for the user)
Label4.Caption:= IntToStr(sizez div 1024) + "Kb';
(Create a second file or overwrite it if it already exists)
while not Eof(f1) do begin //until the end of the first file is reached
//read one byte from the first file
//write one byte to the second file
CloseFile(f1);//close the first file
CloseFile(f2); // close the second file
if IOResult<>0 //If an I/O error occurs
then MessageDlg("Error copying file!", mtError, , 0) //error message
(if there were no errors, then we display a window indicating the successful completion of copying)
ShowMessage("Copied successfully!");

procedure TForm1.ButtonlClick(Sender: TObject);

procedure TForm1.Button2Click(Sender: TObject);
if Open1.Execute then from.Text:= Open1.FileName
else ShowMessage("The file was not opened");

procedure TForm1.Button3Click(Sender: TObject);
if Save1.Execute then where.Text:= Save1.FileName
else ShowMessage(""You have not selected a location to save the file!");

procedure TForm1.Button5Click(Sender: TObject);
DeleteFile(from.Text); //delete the source file

procedure TForm1.Button4Click(Sender: TObject);
if Open1.Execute then del.Text:= Open1.FileName
else ShowMessage("File was not selected");

procedure TForm1.Button6Click(Sender: TObject);
DeleteFile(del.Text); //delete the file
then //check the existence of the file
//display a message about successful deletion
ShowMessage("File deleted!");

⊚ All project files and the executable file of the program discussed are located on the CD included with the book in the Chapter_02 folder.

Subject : « Working with a typed file in Delphi »

Develop an application that allows you to work with a typed file by selecting the appropriate menu item:

File

View

Editing

Seal

Directories

Exit

All data

Addition

By condition

By condition

Adjustment

Documenta

Suppliers

Removal

Application requirements:

    Place all global data types, constants and variables in a separate module (Unit2), which must be connected to other project modules through the File / Use Unit menu item.

    To enter source data into a file (menu items “Adjustment” and “Add”), develop an on-screen input form. Provide verification of the correctness of input data using the OnKeyPress event.

    Viewing data from a file must be implemented by outputting it to a StringGrid table.

    When implementing the “Adjustment” menu item, the “old” values ​​of the fields of the record being adjusted should be displayed on the input form.

    The "Delete" menu item should provide the ability to delete one entry from a file of the user's choice.

    Implement conditional printing using the QuickRep component and an additional text file.

    You can print a document using the Form10.Print method by first placing the necessary information on the form.

    On the form, in addition to the main menu, place:
    - a picture corresponding to the subject area of ​​the task;
    - a toolbar (ToolBar component) and add several SpeedButtons to it, duplicating some main menu items.

    Working with the application should begin by entering a password on a separate form in order to avoid unauthorized access to data.

    When you first open a form containing task main menu items, only the “File” and “Exit” items should be available.

    For buttons, use the BitBtn component, assign a color and font size, as well as an image that matches the meaning.

    If desired, place a meaningful image to the left of the name of some menu items using the Bitmap property (Program Files\Common Files\Borland Shared\Images\Buttons)

    On the “View all records in a file” form, organize a search for a record and ensure that the found record is displayed on a separate form.

Information about the receipt of goods at the warehouse: date of receipt, supplier, product name, price, quantity - must be saved in a typed file. The condition for viewing is a product from the selected supplier. The condition for printing is the receipt of goods on a certain date. The document is a commodity card.

PROCEDURE FOR COMPLETING THE TASK:

    Create a new application

    On Form1, create the main menu according to the task conditions.

    Place the Image1 component on Form1. In the Object Inspector, assign the following properties to the Image1 component:
    Align = alClient

Stretch = true
Picture - file with a picture

    Add a new module File / New / Unit to the project and in the Interface section write

Ttov = record // record structure containing information about the product for
// typed file

DateP:TdateTime; // date of delivery

Postav: string ; // supplier company

Product: string; // Product Name

Cena: real; // the price of the product

Kol:integer; // quantity of goods

Var Tov: Ttov; // a record containing information about a product

F1, F3: file of Ttov; // typed file for storing product information

F2: textFile; // text file for implementing conditional printing

Name_F: string; // Name file

. . . // other variables that will be needed to solve the problem

    Product Directory"(File/New/Form). The “Product Catalog” form must contain ListBox, Edit, Label components and two BitBtn buttons that allow you to save the Edit contents to the ListBox and the entire ListBox contents to a text file. For the ListBox component in the Object Inspector, set the Sorted property to True, then the items will be sorted in alphabetical order.

    In the Object Inspector for the Product Catalog form, select the OnActivate event. Write the program code in the procedure:

If FileExists('tovar.txt') = true then ListBox1.items.LoadFromFile('tovar.txt');

    In the Object Inspector, select the OnClick event for the Add to List button. Write the program code in the procedure:

Listbox1.Items.Append(Edit1.text);

Edit1.Text:= "";

    In the Object Inspector, for the Remove from List button, select the OnClick event. Write the program code in the procedure:

If MessageDlg("Delete entry?", mtConfirmation, , 0) = mrYes

then ListBox1.items.Delete(ListBox1.itemindex);

    In the Object Inspector, select the OnClick event for the Close button. Write the program code in the procedure:

ListBox1.items.SaveToFile('tovar.txt');

    In the Object Inspector, select the OnClick event for the Close button. Write the program code in the procedure: Form3.Close ;

    Do the same with the form " Directory of supplier companies».

    In the procedure for calling the “Products” menu item, enter the program code:
    Form3.Show;

    In the procedure for calling the “Suppliers” menu item, enter the program code:
    Form4.Show;

    Place the SaveDialog1 component on Form1. Write the program code for the menu item procedure " Create»:

If SaveDialog1.Execute = true then

Name_F:= SaveDialog1.FileName ;

AssignFile(F1, Name_F) ;

Rewrite(F1); // the file will be created and opened for writing

CloseFile(F1); // closing file

N1.Enabled:= true; // paragraph menu File

N2.Enabled:= true; // paragraph menu View

N3.Enabled:= true; // paragraph menu Editing

N4.Enabled:= true; // menu item Print

N5.Enabled:= true; // paragraph menu Directories

N6.Enabled:= true; // menu item Exit

    Place the OpenDialog1 component on Form1. Write the program code for the menu item procedure " Open»:

if OpenDialog1.Execute = true then

Name_F:= OpenDialog1.FileName ;

AssignFile(F1, Name_F);

N1.Enabled:= true; // paragraph menu File

N2.Enabled:= true; // paragraph menu View

N3.Enabled:= true; // paragraph menu Editing

N4.Enabled:= true; // menu item Print

N5.Enabled:= true; // paragraph menu Directories

N6.Enabled:= true; // menu item Exit

    In the Object Inspector for Form1, select the OnCreate event. Write the program code in the procedure:

N1.Enabled:= true; // paragraph menu File

N2.Enabled:= false; // paragraph menu View

N3.Enabled:= false; // paragraph menu Editing

N4.Enabled:= false; // menu item Print

N5.Enabled:= false; // paragraph menu Directories

N6.Enabled:= true; // menu item Exit

    Add a new form to the application " Addition» to enter initial data into the file. Place the dateTimePicker1, Combobox1, Combobox2, edit1, edit2, Button1 components on the form. Check the correctness of data entry into the edit1, edit2 components using the OnKeyPress event.

    For Combobox components, disable keyboard input (since data should be selected only from directories). To do this, write the program code in the OnKeyPress event procedure: If not (key in ) then key:= #0;

    In the Object Inspector for the Add form, enter the Caption property as Adding a Record and select the OnActivate event. Write the program code in the procedure:

Exit ; //

Tov.Tovar:= Combobox1.text;

Tov.Postav:= Combobox2.text ;

Reset(f1); // opened a file for writing

Seek(F1, Filesize(F1)); // go to the last record of the file

Write(F1,Tov); // write a record to a file

Edit1.text:= ''; // cleaning

Edit2.text:= '';

ComboBox1.text:= '';

ComboBox2.text:= '';

    Add a new form to the application " View all data" to output data from a file. Place the StringGrid1 component on the form. In the Object Inspector, for the View All Data form, select the OnActivate event. Write the program code in the procedure:

Reset(F1); // opened the file for reading

StringGrid1.RowCount: = FileSize(F1)+1 ; //

width of the first table field

width of the second table field

Stringgrid1.ColWidths := 100; //

Stringgrid1.ColWidths := 100; // width of the fifth table field

Reset(f1); // opened the file for reading

WhiLe not eof(F1) do

Read(F1,tov) ; // read a record from a file

    Add a new form to the application " View by condition" to output data from a file. Place the components Label, ComboBox1, BitBtn1 and StringGrid1 on the form. In the Object Inspector, for the Conditional View form, select the OnActivate event. Write the program code in the procedure:

If FileExists('postav.txt') = true then ComboBox1.items.LoadFromFile('postav.txt');
StringGrid1.visible:= false ;

    In the Object Inspector for the BitBtn1 component, set the Caption property to ‘View’ and select the OnClick event. Write the program code in the procedure:

If ComboBox1.text = '' Then // if no Supplier is selected then...

ShowMessage(‘Fill in all fields!’);

Exit ; // forced exit from the procedure

Reset(F1); // opened the file for reading

WhiLe not eof(F1) do

Read(F1,tov) ; // read a record from a file

If tov.Postav = ComboBox1.text then K: = K + 1 ;

If k = 0 Then // if there is no product from the selected Supplier then...

ShowMessage('There is no product from the selected supplier!');

Exit ; // forced exit from the procedure

StringGrid1.RowCount: = k+1 ; // set the number of rows in the table

StringGrid1.CoLCount: = 5 ; // set the number of columns in the table

StringGrid1. FixedCols:= 0 ; // number of fixed columns

StringGrid1. FixedRows:= 1; // number of fixed lines

Stringgrid1.ColWidths := 100; // width of the first table field

Stringgrid1.ColWidths := 120; // width of the second table field

Stringgrid1.ColWidths := 130; // width of the third table field

Stringgrid1.ColWidths := 100; // width of the fourth table field

Stringgrid1.ColWidths := 100; // width of the fifth table field

StringGrid1.CeLLs := 'Date of Delivery' ;

StringGrid1.CeLLs := ‘Product Name’ ;

StringGrid1.CeLLs := 'Supplier' ;

StringGrid1.CeLLs := ‘Unit price’ ;

StringGrid1.CeLLs := 'Quantity' ;

Reset(f1); // opened the file for reading

i:= 1; // i– table line number for outputting data from the file

WhiLe not eof(F1) do

Read(F1,tov) ; // read a record from a file

If tov.Postav = ComboBox1.text then

StringGrid1.CeLLs := DateToStr(tov.DateP) ;

StringGrid1.CeLLs := tov.Tovar ;

StringGrid1.CeLLs := tov.Postav ;

StringGrid1.CeLLs := FloatToStr(tov.cena) ;

StringGrid1.CeLLs := intToStr(tov.kol) ;

i:= i + 1 ; // move to next line

StringGrid1.visible:= true ;

    Add a new form to the application " Data correction" to change the file entry (for example, Form8). Place the same components on the form as on the “Add” form. Check the correctness of data entry into the edit1, edit2 components using the OnKeyPress event.
    In the Object Inspector for the Data Adjustment form, select the OnActivate event. Write the program code in the procedure:

If FileExists('tovar.txt') = true then ComboBox1.items.LoadFromFile('tovar.txt');

If FileExists('postav.txt') = true then ComboBox2.items.LoadFromFile('postav.txt');

    In the procedure of the “Adjustment” menu item, write the program code:

Form6.Show ; //
Z:= 44; //
// "Adjustment"

In the Object Inspector, for the StringGrid1 component of the View All Data form, select the OnDbLClick event. Write the program code in the procedure:

If z = 44 then

Y:= StringGrid1.Row ; //

Reset (F1); // opened the file for reading

Seek (F1, y – 1) ; //

Read(F1, Tov) ; // read a record from a file

Form8.dateTimePicker1.Date:= Tov.DateP ;

Form8.Combobox1.text:= Tov.Tovar ;

Form8.Combobox2.text:= Tov.Postav ;

Form8.edit1.text:= FLoatToStr(Tov.Cena) ;

Form8.edit2.text:= intToStr(Tov.Kol);

If (Edit1.tetx = '') or (Edit2.text = '') or (ComboBox1.text = '') or (ComboBox2.text = '') Then Begin

ShowMessage(‘Fill in all fields!’);

Exit ; // forced exit from the procedure

Reset (F1); // opened a file for writing

Seek (F1, y – 1) ; // moved in the file to record number y-1

Tov.DateP:= dateTimePicker1.Date;

Tov.Tovar:= Combobox1.text;

Tov.Postav:= Combobox2.text ;

Tov.Cena:= StrToFloat(edit1.text);

Tov.Kol:= StrToInt(edit2.text);

Write(F1,Tov); // write a record to a file

Edit1.text:= ''; // cleaning

Edit2.text:= '';

ComboBox1.text:= '';

ComboBox2.text:= '';

    In the menu item procedure " Removal» write the program code:

Form6.Show ; // calling the “View all data” form
Z:= 55; // a sign that we opened the “View” form from the menu item
// "Delete"

In the Object Inspector, for the StringGrid1 component of the View All Data form, select the OnDblClick event. Complete the procedure with program code:

If z = 55 then

Otv:= MessageDlg ("Delete entry?", mtConfirmation, , 0) ;

if Otv = mrYes then

Y1:= StringGrid1.Row ; // determined the number of the current table row

Y2:= Y1 -1 ; // number of the file entry to be deleted

AssignFile(F3, 'result.dat');

Rewrite(F3); //

Reset (F1); // opened the file for reading

While not eof(F1) do

If FilePos(F1) Y2 then

Read(F1, tov) ; // read a record from a fileF1

Write(F3, tov) ; // wrote an entry to a fileF3

ELSE Read(F1,tov);

Deletefile(Name_F) ; // deleted original file

RenameFile('result.dat', Name_F); // renamed fileresult.dat

    Add a new form to the application " Print by condition" Place the components Label, DateTimePicker, BitBtn on the form.

    Having selected the OnClick event for the “Print” button, write program code into the procedure that ensures the formation of a text file containing records from the typed file that satisfy the print condition:

AssignFile(F2, 'pechat.txt');

Rewrite(F2); // created and opened a file for writing

Reset (F1); // opened the file for reading

K1:= 0; // initial value for counting the number of records for a specified date

While not eof(F1) do

Read(F1, tov) ; //

If DateToStr(tov.DateP) = DateToStr(DateTimePicker1.date) then

D:= DateToStr(DateTimePicker1.date) ;

K1:= K1 + 1; // counting the number of records for a specified date

WriteLN(F2, tov.Tovar: 20, tov.Postav: 20, tov.Cena: 20: 2, tov.Kol: 15) ; // recorded in
text file

    Add a new form (Form10) to the application.

    install the QuickRep1 component on Form10, which is located on the QREPORT page of the component palette;

    in the Object Inspector, select the HasPageHeader subproperty in the Bands property and set it to True, which will ensure that the header is present in
    output document;

    in the Object Inspector, select the HasTitle subproperty in the Bands property and set it to True, which will ensure the presence of a title bar in the output document;

    install the QRStringsBand component, which is located on the QREPORT page of the component palette, on the QuickRep1 component;

    in the Object Inspector for the QuickRep1 component, select the HasPageFooter subproperty in the Bands property and set it to True, which will ensure the presence of a footer in the output document;

    install the QRMemo1 component, which is located on the QREPORT page of the component palette, on the HasPageHeader report strip of the QuickRep1 component. In the Object Inspector, in the Lines property, write down information about the organization to whose warehouse the goods are received;

    install the QRLabel1 component, which is located on the QREPORT page of the component palette, on the HasTitle report strip of the QuickRep1 component. In the Object Inspector, assign the Caption property the value "Information about the receipt of goods for ". In the Object Inspector, change the Font property values ​​to make the document's title stand out from the main information;

    install the QRLabel2 component, which is located on the QREPORT page of the component palette, on the HasTitle report strip of the QuickRep1 component. Complete the program code for the “Print” button with the following line:
    Form10.QRLabel2.Caption:= D ;

    Install the QRExpr1 component on the QRStringsBand component, which is located on the QREPORT page of the component palette. In the Object Inspector, set the Expression property to QRStringsBand1;

    install the QRLabel3 component, which is located on the QREPORT page of the component palette, on the HasPageFooter report strip of the QuickRep1 component. In the Object Inspector, assign the Caption property the value “Date and time the document was created”;

    install the QRSysData1 component, which is located on the QREPORT page of the component palette, on the HasPageFooter report strip of the QuickRep1 component. In the Object Inspector, assign the Data property the value qrsDateTime;

    install the QRLabel4 component, which is located on the QREPORT page of the component palette, on the HasPageFooter report strip of the QuickRep1 component. In the Object Inspector, assign the Caption property the value "Total number of products:";

    install the QRLabel5 component, which is located on the QREPORT page of the component palette, on the HasPageFooter report strip of the QuickRep1 component. Add the following line to the program code of the "PRINT" button:
    Form10.QRLabel5.Caption:= intToStr(k1);

    add the following program code to the body of the procedure-handler for the event "Pressing the PRINT button":

ShowMessage('There are no deliveries for the selected date!');

Exit ; // forced exit from the procedure

form10.QRStringsBand1.Items.Clear;

form10.QRStringsBand1.Items.LoadFromFile("pechat.txt");

form10.QRExpr1.AutoSize:=false;

form10.QRExpr1.AutoStretch:=true;

form10.QRExpr1.Left:=0;

form10.QRExpr1.Width:=form10.QRStringsBand1.Width;

form10.QuickRep1.Preview;

    Add a new form (Form11) to the application. In the Object Inspector, assign the Caption property the value "Product Card". Place on the form the same components as on the “Add” form, but instead of the dateTimePicker1, Combobox1 and Combobox2 components, use the Edit3, Edit4 and Edit5 components, and rename the “Save” button to “Print”

    In the menu item procedure " Printing a document» write the program code:

Form6.Show ; // calling the “View all data” form
Z:= 66; // a sign that we have opened the “View” form from the menu item
// "Print document"

In the Object Inspector, for the StringGrid1 component of the View All Data form, select the OnDbLClick event. Complete the procedure with program code:

If z = 66 then

Y:= StringGrid1.Row ; // determined the number of the current table row

Reset (F1); // opened the file for reading

Seek (F1, y – 1) ; // moved in the file to record number y-1

Read(F1, Tov) ; // read a record from a file

CloseFile(F1);

Form11.Edit5.text:= DateToStr(Tov.DateP) ;

Form11.Edit4.text:= Tov.Tovar ;

Form11.Edit3.text:= Tov.Postav ;

Form11.Edit1.text:= FLoatToStr(Tov.Cena) ;

Form11.Edit2.text:= intToStr (Tov.Kol) ;

    In the Object Inspector, for the Print button on Form11, select the OnClick event. Write the program code in the procedure: Form11.Print ;

If Edit1.text = … then

End ELSE ShowMessage ('Password is incorrect');


In the Object Inspector, for the Find button, select the OnClick event. Write the program code in the procedure:

Reset (F1); // opened the file for reading

While not eof(F1) do

Read(F1, tov) ; // read a record from a typed file

If (DateToStr(tov.DateP) = DateToStr(DateTimePicker1.date)) and (tov.Postav = Combobox1.text) then

Form13. Label6. caption:= DateToStr (Tov.DateP) ;

Form13. Label7. caption:= Tov.Tovar ;

Form13. Label8. caption:= Tov.Postav ;

Form13. Label9. caption:= FloatToStr(Tov.Cena) ;

Form13. Label10. caption:= IntToStr (Tov.Kol) ;

CloseFile(F1);

If XX = 0 then ShowMessage (‘No data…’) ;