Delphi File Operations (compare All)

Source: Internet
Author: User
Tags decrypt ord

The default in Delphi is input and output two file variables, use can be used without definition, directly.
But: input: read-only, output: write only. Take care to avoid causing an exception.

A file is a collection of data that is identified by a file name, which is usually stored on disk. The source program, student records, graphics, music, etc. can be stored as files on disk. The operating system manages the data in files, that is, if you want to read data on external memory media, you must first locate the file you specified by file name, and then read the data from that file. To store data on external memory media, you must also create a file (identified by the file name) before you can output data to it.
When a program is running, it is often necessary to output some data (the final result or intermediate data that is running) to disk, and then enter it from disk to computer memory later. This will use a disk file.
1. File types
File is a type specifier that can be used to define file variables or to define some new types. The following 3 types of files are supported in Delphi: Text files, type files, and untyped files (also known as binary files). The following sequence describes the definition of 3 file type variables and how to use them.
In Delphi program design, the operation of any kind of file can be summed up as: open _ Read/write _ close.
2. Text files
(* * * REPRINT PLEASE note-this article source: Nanshan Gudo (Nsgtao) Baidu Space: http://hi.baidu.com/nsgtao/* * * * * * *)
2.1 Concepts of text files

The textfile type is defined in Delphi as a text file, consisting of the ASCII code of the character and the minimum Access unit as a character. A text file is also known as an ASCII code file. Use the common text editor to navigate through the contents of the branch.
A text file is read and written in the Unit of action. Because the length of each line is not necessarily the same, the exact position of the given row in the file cannot be computed, and thus can be read and written sequentially. It is not allowed to read and write at the same time on an open text file.

2.2 Definition of a text file variable
The syntax format for defining file variables is as follows:
var < file variable name >:TextFile;
For example, Var mytextfile:textfile; a text file variable mytextfile is defined, and a text file can be referenced by this variable below.

2.3 Use of text files

(1) File variables and file associations
Before you can use file variables for file operations, you need to associate the file variable with the file you want to manipulate, i.e. assign a value to the file variable name. File variable assignment can use procedure AssignFile, the description syntax of the procedure is as follows:
Procedure AssignFile (Var f;filename:string);
Where F is the name of the file variable and is defined as an untyped parameter for compatibility with all file types; filename is a file name string that is the full name of the document that includes the path. For example, AssignFile (f, ' E:\delphi\program\extl.txt ') associates the file variable f with the specified file E:\delphi\program\extl.txt. All subsequent operations on the variable F are actions on the specified file.

(2) Open file with file variable
There are 3 ways to open a file using a different procedure:
Procedure Rewrite (var f~file[;recsize:word]);
This process creates and opens a file that you can write to. The f here is a file variable that has been associated with the specified file name. For an existing file, the operation overwrites the original file, and if the file does not exist, a new empty file is created. If the type file (described in the next section), Recsize can be used to specify the size.
Procedure Reset (var f:file[;recsize:word]);
Using the reset procedure to open a file in a read-only manner, you can only read data from the file. F is a file variable, and when the file is opened, the file pointer points to the beginning of the file. If you attempt to open a nonexistent file with the reset procedure, an I/O error occurs.
Procedure. Append (var F: ' Fext);
Use the Append procedure to append text to an existing file, which is used only for text files. When you open a file with the append process, the file pointer points to the end of the file, and the data that you enter later is appended to the file's original data. The file that the procedure opens (that is, the file associated with F) must exist, or I/O errors will also occur.
(3) Read/write files
① reads the contents of the file. After you open a file in a read manner, you can use the Read and READLN statements to read the contents of the file, with the declaration code in the following format:
Procedure read ([var F: ' Fext;] V1[,v2,..., Vn]);
Procedure Readln ([var F: ' Text;] v1[,v2,,VN]);
Where f is the file variable. V1, v2 、...、 vn, etc. are variables that need to be entered, and their types can be strings, characters, integers, and real types. The difference between read and READLN is that after reading the data, the file pointer is moved to the next line, and the data between the last read and the carriage return is ignored.
When reading a string, you must use the READLN procedure, or read a row of data, and then use read to read the string to get an empty string. When reading integer and real data, the data in the file is separated by spaces and must conform to the data format, otherwise an I/O error will result.
When reading a file, you must also determine whether the file pointer has reached the end of the file, which can be judged with the EOF function, the declaration code is as follows:
function eof[(' var F: ' Rext)]:boolean;
The function returns a value of True when the file pointer refers to the trailer.
② writes data to a file. After you open the file in writing, you can write the data to it, and the write data uses the write and writeln procedures with the following declaration code:
Procedure Writeln ([var F: ' Rext;] P 1[,P2,..., PN]);
Procedure write ([var F: ' Rext;] P 1[,p2, ' • ', PN]);
Like Read, P 1, p2 、...、 pn are variables that need to be output, such as strings, characters, integers, and real types. A writeln will append a carriage return and a newline character after the data is written, and the next data to be written will be written on a new line.
When writing human data, the system automatically converts the data into a string form, 1) The ~ASCII code is saved in the file.

(4) Closing files with file variables
Regardless of the input or output, the file should be closed after the file operation is complete. Close the file using the CloseFile procedure with the following declaration code:
Procedure CloseFile (var F);
When you close a file, the system frees the resources that are used to open the file. In particular, when writing a file, when the write and writeln procedures are called, the data is written to the memory buffer, and the data is actually written to the disk file only when the buffer is full or closed, so it is possible to lose data after writing the data without closing the file.
Example 2. 15 Use the Rewrite () procedure to create a text file in the current directory where the program is running. TXT, and add 5 lines of text to the file.

Var
Textf:textfile;//define File variables Textf
s:string;
I:integer;
Begin
AssignFile (TEXTF, ' file. TXT ');//TEXTF The file variable to the current directory "file." TXT "file association
Rewrite (TEXTF); Create a file or open an existing file to overwrite it
For I:=1 to 5 do
Begin
S: = ' this is line# ';
Writeln (Textf,s,i);
End
CloseFile (TEXTF);//close open files TEXTF
End
The created file contains 5 lines of text, such as the 3rd behavior: this is line#3.
To append new text to a file that already exists, you should change the rewrite to append. The above procedure is to write a string and an integer to the file. In fact, Object Pascal can handle all data types like this. The following program shows how to read data from a text file.
Write file
Var
F:textfile; Declaration variables
Begin
AssignFile (F, ' c:\ek.txt '); Make the variable F and C:\ek.txt connected
ReWrite (F); {Create A new file named Ek.txt}
Writeln (F, ' You want to write the contents of the text file '); Write file
CloseFile (F); Release variable F
End;
Read file
Var
F:textfile;
str:string;
Begin
AssignFile (F, ' c:\ek.txt '); {Assigns the Filename}
Reset (F); {Opens the file for reading}
READLN (F, str);
ShowMessage (' 1. Line of Textfile: ' +str);
CloseFile (F); {Closes file F}
End;

The following turn from http://blog.csdn.net/xwchen/archive/2007/07/26/1710410.aspx
var F:text;
...
AssignFile (F, ' c:\1.txt ');
ReWrite (f);
Writeln (f, ' This is a test ');
CloseFile (f);
...
Where rewrite is the new file, and if you switch to reset, open the file
Writeln writes to line and wraps, write does not wrap, Readln reads a line and wraps, read reads but does not break lines


There are many ways to read and write files in Delphi:
I'll give you a sticker:
We often encounter the need to process files, directories, and drives in program design, and this chapter will tell you how to handle different types of files. This chapter includes how to use the input/output of the T F i l e S t r e a class encapsulated file and how to utilize the main features of the 3 2-bit WI n d o w S-memory-mapped file. You will learn how to create a T-M e m o r y m a p p e d F i-E class that encapsulates the memory-mapped file function and use it to make text queries in a text file. This chapter also provides some methods for selecting drives, querying files in a tree directory, and getting file version information. This chapter will give you an in-depth understanding of files, directories, and drives.
Processing file input/output
You will be working on three files: text files, type files, and binaries.
The following sections describe the file input/output. A text file refers to a S C i i text that can be read by any text editor. A type file refers to a file that contains a data type defined by a programmer. A binary file contains all other types, which are collectively referred to as files that contain arbitrary or unformatted data.

Processing of text files
This section describes methods for working with text files using procedures and functions built into the object Pascal run-time library. Before you make any processing of a text file, you first open the text file. Declaring variables: You can refer to a text file by using this variable.
Opening a file takes two steps: The first is a s s i G n F i l e (), which can associate a file variable with a file. For example: At this point, you can take the second step: Open the file. There are three ways to open a file: Use the r e W r i t E () procedure to create and open a file, and for an existing file, this action will overwrite the file, open a file read-only using the R e S e t () procedure, and append text to the existing file using the Append () procedure.
Note Reset () opens the type file and the untyped file in a read-write manner. You can use the C l o S e F i l e () to close an open file. The following example is a function of various calls.

Opening and closing of files
AssignFile: To correlate an external file name with a variable
Reset: Open a file that exists
Rewrite: Create and open a new file (or overwrite the original file)
Append: Open a file as added (only for text files)
CloseFile: Close an open file
FileOpen: Opens a specific file and returns a file handle
Filecreate: Creates a file with a given file name and returns a file handle
FileClose: Closing a file with a specific handle
The back three files are intended for internal use by the system and are often used in the programming of file replication. The objects they manipulate are file handles rather than file variables.

File location
Seek: Moves the current position of the file to the specified section
Filepos: Returns the current location of the file
Eoln: Return line End Flag
EOF: Return end of File flag
FileSeek: Changing the position of the current file pointer

One more question, how to tell if the file is open? Do you want to close the file after reading and writing, and then open it next time you read or write?

Normally, this is the case.


With TFileStream
For the file operation through a byte array, in the FTP is often used to, I also in the Delphi Call Web Service to upload and download files to find these two functions, very useful, recommend to everyone. (Disclaimer: Not written by me)

1. Generating a byte array file

Procedure Bytearraytofile (const bytearray:tbytedynarray; const filename:string);
Var
Count:integer;
F:file of Byte;
Ptemp:pointer;
Begin
AssignFile (F, FileName);
Rewrite (F);
Try
Count: = Length (ByteArray);
Ptemp: = @ByteArray [0];
Blockwrite (F, ptemp^, Count);
Finally
CloseFile (F);
End
End

2. Generating a byte array of files

function Fiietobytearray (const filename:string): Tbytedynarray;
Const
block_size=1024;
Var
Bytesread,bytestowrite,count:integer;
F:file of Byte;
Ptemp:pointer;
Begin
AssignFile (F, FileName);
Reset (F);
Try
Count: = FileSize (F);
SetLength (Result, Count);
Ptemp: = @Result [0];
Bytesread: = block_size;
while (bytesread = block_size) do
Begin
Bytestowrite: = Min (Count, block_size);
Blockread (F, ptemp^, Bytestowrite, bytesread);
Ptemp: = Pointer (Longint (ptemp) + block_size);
Count: = Count-bytesread;
End
Finally
CloseFile (F);
End
End


function Encrypt (mstr:string; mkey:string): string;
Var
I, J:integer;
Begin
J: = 1;
Result: = ';
For I: = 1 to Length (MSTR) does begin
Result: = result + Char (ORD (Mstr[i]) XOR Ord (Mkey[j]));
If J + 1 <= Length (Mkey) Then
INC (J)
else J: = 1;
End
{Add your own steps}
End


function Decrypt (mstr:string; mkey:string): string;
Var
I, J:integer;
Begin
J: = 1;
Result: = ';
{Add your own steps}
For I: = 1 to Length (MSTR) does begin
Result: = result + Char (ORD (Mstr[i]) XOR Ord (Mkey[j]));
If J + 1 <= Length (Mkey) Then
INC (J)
else J: = 1;
End
End

Procedure Tform1.button1click (Sender:tobject);
Const
CKey1 = ' Who wants to try how to break ';
CKey2 = ' I don't want to play like this (1) I don't want to play this way (2) I don't want to play this way (3) ';
CKey3 = ' Memo2.text: = Decrypt (Encrypt (Memo1.text, Ckey), ckey); ';
Var
s:string; The characters after the encryption
Begin
S: = Encrypt (Encrypt (Encrypt (Memo1.text, CKey1), CKey2), CKey3);
ShowMessage (S);
Memo2.text: = Decrypt (Decrypt (Decrypt (S, CKey3), CKey2), cKey1);
End

http://blog.csdn.net/zisongjia/article/details/70173090

Delphi File Operations (compare All)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.