In the process of programming, the file operation is a frequently used problem. In C Builder, you can use a variety of ways to operate file operations. Here I follow the following sections, this is:
1. File operation based on C;
2, based on C file operation;
3. File operation based on WINAPI;
4, file operation based on the BCB library;
5, the operation of special documents. This time I first wrote the first one, I will write other parts in my homepage later.
壹, C's-based file operation
In ANSI C, the operation of the file is divided into two ways, namely streaming file operations, and I / O file operations, the following introduces.
First, flow file operation
This way's file operation has an important structure file, file defined in stdio.h as follows:
Typedef struct {
INT level; / * Fill / Empty level of buffer * /
Unsigned flags; / * file status flags * /
Char fd; / * file descriptor * /
Unsigned char hold; / * ungetc char if no buffer * /
Int bsize; / * buffer size * /
Unsigned char _far * buffer; / * data transfer buffer * /
Unsigned char _far * curp; / * current activity Pointer * /
Unsigned istemp; / * Temporary File Indicator * /
Short token; / * buy for validity checking * /
} File; / * this is the file object * /
File This structure contains the basic properties of the file operation, and the operation of the file is performed through the pointer of this structure. This file is used to see the following table.
Function function
Fopen () open flow
Fclose () close flow
FPUTC () writes a character to the stream
FGetc () reads a character from the stream
FSEEK () positioned in the stream to the specified character
FPUTS () write string to stream
FGETS () reads a line or specifies a character in the stream
FPRINTF () outputs to the flow in format
fscanf () reads from the stream
Feof () return true value when arriving at the end of the file
FERROR () Returns its value when an error occurs
ReWind () reset file locator to the beginning of the file
REMOVE () delete files
FREAD () reads the specified number of characters from the stream
FWRITE () Write the specified number of characters in the stream
TMPFile () Generates a temporary file stream
Tmpnam () Generates a unique file name
Let's introduce these functions.
FOPEN ()
FOPEN's prototype is: file * fopen (const char * filename, const char * mode), FOPEN implementation three functions
Open a stream for use
Connect a file and this stream
Return to this stream back a Filr pointer
Parameter filename points to the file name to be opened, Mode represents a string that opens the state, and the value is as follows.
String meaning
"R" opens the file in read-only mode
"w" opens only files
"a" opens the file in an additional method
"R " opens files in read / write, such as no file error
"W " opens files in read / write, such as no file generation new file
A file can be opened in text mode or binary mode. These differences are: Enter the carriage return in text mode as a character '/ n', and binary mode thinks it is two characters 0x0d, 0x0a; if in the file Read 0x1b, text mode will consider this is the file ending, that is, the binary model does not process the file, and the text mode will be converted accordingly on the data. The system default is to open in text mode, you can modify the value of all variable _fmode to modify this setting, such as _fmode = o_text; set the default open mode as text mode; _fmode = o_binary; set the default open mode is binary mode.
We can also specify open mode in the mode string, such as "RB" to open read-only files, "W T" or "WT " in binary mode indicate that the read / write file in text mode is opened.
This function returns a FILE pointer, so there is no initialization after a FILE pointer, but uses fopen () to return a pointer and connected to a specific file, if success or failure, return null.
example:
File * fp;
IF (FP = FOPEN ("123.456", "WB")))
PUTS ("Open File Success");
Else
PUTS ("Open File Beail";
2.fclose ()
Fclose () function is to close file with fopen (), whose prototype is: int Fclose (file * fp); if successful, return 0, failback Returns EOF.
At the end of the program, you must remember to close the open file, otherwise it may cause data loss, and I have often made such a problem.
Example: fclose (fp);
3.FPUTC ()
Write a character, the prototype is int FPUTC (INT C, FILE * stream); successfully returns this character, failed to return EOF.
Example: FPUTC ('x', fp);
4.FGetc ()
Read a character from the stream, the prototype is int FPUTC (file * stream); successfully returns this character, failed to return EOF.
Example: char ch1 = fgetc (fp);
5. fseek ()
This function is typically used in a file in binary mode. The function is to position the location specified in the stream. The prototype is int FSeek (file * stream, long offset, int because if it successfully returns 0, the parameter OFFSET is the number of moving characters Whence is the benchmark of the mobile, the value is
Symbol constant value reference position
SEEK_SET 0 file
Seek_cur 1 where the current read is written
SEEK_END 2 file tail
Example: FSeek (FP, 1234L, seek_cur); // Put the read-write position from the current position to the current position upward 1234 bytes (L suffix represents long integer)
FSEEK (FP, 0L, 2); // Move read and write position to the file
6.FPUTS ()
Write a string into the stream, prototype int FPUTS (Const Char * S, File * Stream);
Example: FPUTS ("i love you", fp);
7.FGETS ()
Read a row or specify a character from the stream, the prototype is char * FGETS (Char * S, INT N, FILE * STREAM); read N-1 characters from the stream unless the parameter S is to receive characters String, if success, return the pointer of S, otherwise return NULL.
Example: If the text of the current location of a file is as follows
Love, I Have
But ........ If you use
FGETS (str1, 4, file1);
Then start Str1 = "LOV", read 4-1 = 3 characters, and if used
FGETS (str1, 23, file1);
The Str = "Love, I Have" is executed, and one line is read (not including '/ n').
8.fprintf ()
Enter the stream in format, whose prototype is int fprintf (file * stream, const char * format [, argument, ...]); its usage is the same as Printf (), but it is not written to the console, but write flow Stop
Example: fprintf (fp, "% 2d% s", 4, "hahaha");
9.fscanf ()
Read from the stream, the prototype is int Fscanf (file * stream, const char * format [, address, ...]); its usage is the same as scanf (), but not from the console, but Remind from the flow.
Example: fscanf (FP, "% D% D", & x, & y);
10.FeOf ()
Detecting if it has arrived in the file, it is true, otherwise it returns 0, its prototype is int Feof (File * stream);
Example: IF (Feof (fp)) Printf ("has arrived in the file tail");
11.FERROR ()
The prototype is int Ferror (file * stream); returning the most recent error code, can be cleared by clearrr (), the prototype of the Clearerr () is Void Clearerr (File * stream);
Example: Printf ("% D", FERROR (FP));
12.rewind ()
Starting the current read and write position back, the prototype is Void Rewind (file * stream); in fact this function is equivalent to FSeek (FP, 0L, seek_set);
Example: Rewind (fp);
12.Remove ()
Deleting files, prototype is int Remove (const char * filename); the parameter is the file name to be deleted, and successfully returns 0.
Example: Remove ("c: //io.sys");
13.fread ()
Read the specified number of characters from the stream, the prototype is Size_T FREAD (Void * PTR, SIZE_T SIZE, SIZE_T N, File * Stream); the parameter PTR is the data saved, and the pointer of the void * can be replaced with any type of pointer. Such as char *, int *, etc.; size is the number of bytes per piece; n is the number of pieces read, if successful, return the number of blocks actually read (not byte), this function is generally used In the file opened in binary mode.
example:
Char x [4230];
FILE * file1 = fopen ("c: //msdos.sys", "r");
Fread (x, 200, 12, file1); // Total 200 * 12 = 2400 bytes
14.fwrite ()
Corresponding to the FREAD, write the specified data in the stream, the prototype is size_t fwrite (const void * ptr, size_t size, size_t n, file * stream); parameter PTR is the data pointer to be written, and the pointer of Void * can be used any type The pointer is replaced, such as char *, int *, etc.); size is the number of bytes per piece; N is the number of blocks to write, if successful, return the number of blocks actually written (not byte), This function is generally used in a file opened in binary mode. example:
Char x [] = "i love you";
Fwire (x, 6, 12, fp); // Write 6 * 12 = 72 bytes
Write "i love" 12 times in FP, a total of 72 bytes
15.TMPFile ()
Its prototype is file * tmpfile (void); generating a temporary file, open in the mode of "W B", and returns this temporary stream pointer if it returns NULL. This file will be automatically deleted at the end of the program.
Example: file * fp = tmpfile ();
16.TMPNAM ();
Its prototype is char * TMPNAM (Char * s); generating a unique file name, in fact, TMPFile () calls this function, parameter S is used to save the obtained file name, and return this pointer, if it fails, return NULL.
Example: TMPNAM (STR1);
Second, direct I / O file operation
This is another file operation provided by c, which is the process of completing the file by direct storage / taking the file, and the above-mentioned streaming file operation is performed by the buffer; the flow file operation is around a FILE The pointer is carried out, and this type of file operation is performed around the "handle" of a file, what is a handle? It is an integer that is the unique number of marks that the system is used to identify a file (in Windows, the concept of handle to all devices). These files are commonly used functions, these functions and some symbols used in IO.H and FCNTL.H, and the corresponding header file is added when used.
Function description
Open () opens a file and returns its handle
Close () Close a handle
Lseek () positioned to the specified location of the file
Read () block read files
Write () block writes
EOF () test file end
FileLength () acquisition file length
Rename () renamed files
chsize () change the length of the file
Here, these functions will be described:
Open ()
Open a file and return its handle, if it fails, a value of less than 0 is returned, the prototype is int open (const char * path, int access [, unsigned mode]); parameter PATH is the file name to open, Access is Open mode, Mode is optional. Represents the properties of the file, mainly used in the UNIX system, there is no meaning in DOS / Windows. The open mode of the file is as follows.
Symbol mean symbol meaning symbol meaning
O_rdonly read-only mode o_wronly only write mode o_rdwr read / write method
O_ndlay is used for UNIX system o_append append mode o_creat If the file does not exist, create
O_trunc cuts the file length as 0 O_EXCL and O_CREAT, if the file is returned to an error O_BINARY binary method
O_text text method
For multiple requirements, you can use the "|" operator to connect, such as O_APpend | O_Text represents the file in text mode and append mode.
Example: int Handle = Open ("c: //msdos.sys", o_binary | o_creat | o_write) 2.close ()
Close a handle, the prototype is int close (int Handle); if you successfully return 0
Example: Close (Handle)
3.LSeek ()
Located to the specified location, the prototype is: Long Lseek (int.comwhere); parameter offset is the amount of movement, Romwhere is the moving reference location, the value, and the previously speaking FSeek (), seek_set: file The first; seek_cur: file current location; seek_end: file end. This function returns new access location after execution.
example:
Lseek (Handle, -1234L, seek_cur); // Put the access location from the current location to 1234 bytes.
X = lseek (hnd1, 0l, seek_ek_ek); // Move the access position to the end of the file, X = the position of the file is the length of the file
4.Read ()
Read a piece from a file, the prototype is int (int Handle, Void * BUF, UNSIGNED LEN); the parameter buf saves the read data, and LEN is the byte read. The function returns bytes actually read.
Example: Char x [200]; Read (HND1, X, 200);
5.write ()
Write a piece of data into the file, the prototype is int Write (int Handle, Void * BUF, UNSIGNED LEN); the meaning of the parameter is READ (), returns the byte that is actually written.
Example: char x [] = "I love you"; Write (Handle, X, Strlen (x));
7.eof ()
Similar to FeOf (), whether the test file is end, is it returned 1, otherwise it returns 0; the prototype is: int EOF (INT Handle);
Example: While (! EOF (Handle1)) {...};
8.FileLength ()
Returns the file length, the prototype is long filength; it is equivalent to Lseek (Handle, 0L, seek_end)
Example: long x = fileLength;
9.Rename ()
Rename the file, the prototype is int Rename (const char * newname); the parameter OldName is the old file name, and NewName is a new file name. Success return 0
Example: Rename ("c: //config.sys", "c: //config.w40");
10.chsize ();
Change the length of the file, the prototype is int CHSize (INT HANDLE, long size); parameter size indicates a new length of the file, and successfully returns 0, otherwise returns -1, if the specified length is less than the file length, the file is shorted; if specified The length is greater than the file length, then makes '/ 0' after the file.
Example: chsize (handle, 0x12345);
-------------------------------------------------- ----------------------------
----
If familiar with compile may find that this method and assembly language DOS function call sentence handle file operation is like, such as Open () is like the 3ch function call of the DOS service, in fact, this operation has two types of functions are direct Finished with DOS function, such as _open (), _ dos_open (), etc. Interested in searching for BCB help. The same flow is the same, which also provides a function of the Unicode character operation, such as _wopen (), etc., used for wide character programming under 9x / NT, interested in the help of the BCB.
In addition, such operations are LOCK (), unlock (), locking () or the like for multi-user operation, but not much in BCB, I will not introduce, but if I want to write with C CGI, these are necessary, if you have this requirement, then you have to look good.
Here, I will introduce C-based file operations. The next article will introduce the C file operation, so stay tuned.
In C , there is a stream class, all I / O is based on this "stream" class, including the file I / O we want to know, and Stream has two important operators:
1, insert (<<)
Output data to stream. For example, the system has a default standard output stream (COUT), in general, the display, so cout << "Write stdout" << '/ n'; "Write Stdout" and wrap characters ('/ n') outputs to standard output flow.
2, the parser (>>)
Enter data from the stream. For example, the system has a default standard input stream (CIN). In general, the keyboard is referred to, so CIN >> X; represents data that reads a specified type (ie, the type of variable x) from the standard input stream .
In C , the operation of the file is implemented by Stream's sub-FSTREAM (File Stream), so use this way to operate files, you must join the header file FStream.h. Here, this type of file operation process will come.
First, open the file
In the FSTREAM class, there is a member function Open (), which is used to open the file, its prototype is:
Void Open (Const Char * FileName, INT MODE, INT Access);
parameter:
Filename: The name of the file to open
Mode: Way to open the file
Access: Opens the properties of the file
Open the file is defined in class iOS (the base class of all stream I / O classes), the common value is as follows:
ios :: app: Open files in appended way
iOS :: ATE: After the file is opened, locate it to the file, iOS: app contains this property
iOS :: binary: Open file in binary, the default approach is text. From the different ways to see the forebet
ios :: in: File opens in an input mode
iOS :: out: file open in output mode
iOS :: NOCREATE: Do not build files, so open failure when the file does not exist
iOS :: NorePlace: If the file is not overwritten, if the file is failed when the file is opened.
iOS :: Trunc: If the file exists, set the file length to 0
You can use "or" to connect the above properties, such as ios :: out | os :: binary
Opens the property of the file is:
0: Ordinary file, open access
1: Read only files
2: Implied file
4: System file
You can use "or" or " " to connect the above properties, such as 3 or 1 | 2 to open the file with read only and implied attributes.
For example: Open files in binary inputs C: /config.sys
FSTREAM FILE1;
File1.Open ("C: //config.sys", ios :: binary | ios :: in, 0);
If the Open function only has a file name, the Open / write ordinary file is opened, namely:
File1.Open ("c: //config.sys"); <=> file1.Open ("c: //config.sys", ios :: in | os :: out, 0);
In addition, FStream also has the same constructor as Open (), for the above example, you can open the file when defined:
FSTREAM file1 ("c: //config.sys");
In particular, FStream has two subcategories: IFStream (Input File Stream) and OFSTream (Output File Stream), ifstream defaults to open files in an input mode, and the OFSTream is open in an output mode by default.
Ifstream file2 ("c: //pdos.def"); // Open file in an input mode
OFSTREAM file3 ("c: //x.123"); // Open file in output
Therefore, in practical applications, select different classes as needed: If you want to open in an input mode, use ifstream to define; if you want to open it in an output, use OFStream to define; if you want to input / Open the output, use FStream to define.
Second, close the file
After the file is opened, it must be turned off after using the file. FStream provides the member function close () to complete this, such as file1.close (); close the file connected to the file1.
Third, read and write files
Reading and writing files is divided into text files and binary reads. For the reading of text files, it is relatively simple, with insertware and parser can be used; and for binary reading is more complicated, it is detailed Introduce these two ways
1, reading and writing of text files
The reading and writing of the text file is simple: use the insert (<<) to output to the file; use the quote (>>) from the file input. Suppose File1 is opened in an input, and FILE2 is turned on. Examples are as follows:
File2 << "i love you"; // Write the string "i love you"
INT I;
File1 >> i; // Enter an integer value from the file.
This approach has a simple formatting ability, such as the specified output is 16, and the specific format has some
Moderator function input / output
Dec formatted to decimal numerical data input and output
ENDL outputs a newline and refreshed this stream output
ENDS output an empty character output
HEX formatted for hexadecimal numerical data input and output
OCT formatted as an octal numerical data input and output
SetPxecision (int P) Sets the precision bit output of floating point numbers
For example, as you want to use 123 as a hexadecimal output: file1 << HEX << 123; to output 3.1415926 with 5-bit accuracy: file1 << setpxecision (5) << 3.1415926.2, binary reading
1PUT ()
The PUT () function writes a character to the stream, whose prototype is OFSTream & Put (Char CH), is also relatively simple, such as file1.put ('c'); is to write a character 'c'.
2Get ()
The get () function is flexible, there are three commonly used overload form:
One is the form of PUT (): ifstream & Get (CHAR & Ch); the function is to read a character from the stream, and the result is saved in the reference CH, if the file is tail, return empty characters. Such as file2.get (x); indicates that a character is read from the file and saves the read characters in X.
Another prototype of the overloaded form is: int GET (); this form is to return a character from the stream, if the file is reached, returns EOF, such as x = file2.get (); and the above example function is the same .
There is also a form of prototype: ifstream & get (char * buf, int num, char delim = '/ n'); this form reads characters into arrays pointed to by BUF until the NUM characters are read or encountered. The characters specified by Delim, if Delim is not used, the default quotation '/ n' will be used. E.g:
FILE2.GET (STR1, 127, 'A'); // Read characters from the file to the string STR1, and terminate when character 'a' is encountered or read 127 characters.
3 read and write data blocks
To read the binary data block, use the member function read () and write () member functions, their prototypes are as follows:
Read (unsigned char * buf, int Num);
Write (Const unsigned char * buf, int num);
Read () Reads NUM characters from the file to the cache pointing to the BUF. If you go to the end of the file when you have not read NUM characters, you can use the member function Int gcount (); to get the actual number of characters Write () writes NUM characters from the BUF to the NUM character to the file, it is worth noting that the type of cache is unsigned char *, sometimes the type conversion may be required.
example:
UNSIGNED Char str1 [] = "i love you";
INT N;
IFStream in ("xxx.xxx");
OFSTREAM OUT ("YYY.YYY");
Out.write (str1, str1)); // write string STR1 all in Yyy.YYY
IN.READ ((unsigned char *) n, sizeof (n)); // Read the specified integer from xxx.xxx, pay attention to type conversion
In.Close (); out.close ();
Fourth, detect EOF
Member function EOF () is used to detect whether to reach the file, if the end of the file returns a non-0 value, otherwise returns 0. The prototype is int EOF ();
Example: if (in.eof ()) showMessage ("already reaches the file tail!");
V. File positioning
Unlike C file operations, the C I / O system manages two pointers associated with a file. One is a read pointer, which indicates that the input is operated in the file; the other is the write pointer, which is the next time the next time. The corresponding pointer automatically changes each time the input or output is performed. Therefore, the C file position is divided into the positioning of the read position and the write position. The corresponding member function is SEEKG () and seekp (), and seekg () is setting the read position, and the Seekp is set. Their most common forms are as follows: Istream & Seekg (STREAMOFF OFFSET, SEEK_DIR ORIGIN);
Ostream & Seekp (streamoff offset, seek_dir origin);
Streamoff is defined in iostream.h, defines the maximum value that the offset OFFSET can achieve, seek_dir represents the movement of the baseline, an enumeration with the following value:
ios :: beg: the beginning of the file
iOS :: cur: file current location
iOS :: End: File end
These two functions are generally used for binary, because the text files may differ from the expected values because the text file is interpreted by the system.
example:
File1.seekg (1234, iOS :: Cur); // Put the read pointer of the file from the current location 1234 bytes
File2.seekp (1234, iOS :: beg); // Put the file's write pointer from the beginning of the file 1234 bytes
-------------------------------------------------- ------------------------------
With these knowledge, we can complete the operation of the file. Of course, there are still many member functions I have not introduced, but these we can do most of the needs, this file operation method is what I prefer. One method is flexible than C, and it is versatile than BCB functions and WinAPI functions.
Next time, I will introduce the library function of the file operation provided by the BCB.
The function of file operation is also provided in the BCB, and the functions of these functions are substantially the same, but such functions and BCB relationships are close to the BCB's ANSISTRING and other data types, in this way The file operation is the most convenient, and I will introduce this file in detail below.
In this file operation function provided by BCB, it can be divided into three types, which is: 1, file name function, 2, file management function; 3, file I / O function.
1, file name function
File name functions can operate on the name of the file, the subdirectories, drives, and extensions. The following table lists these functions and its features.
Function description
ExpandFileName () Returns the full path of the file (including drive, path)
Extractfileext () draws extensions from the file name
ExtractFileName () Extract the file name without the path from the file name
ExtractFilePath () extracts the path name from the file name
ExtractFileDir () extracts the directory name from the file name
ExtractFileDrive () extracts the drive name from the file name
Changefileext () changes the extension of the file
ExpanduncFileName () Returns the full path to the file containing the network drive
ExtractRELATIVEPATH () extracts relative path information from the file name
ExtractShortPathname () Transforms file names to DOS 8 · 3 format
Matchesmask () Check if the file matches the specified file name format
Let's introduce these functions below:
(1) ExpadFileName ()
Prototype: Extern package anstring __fastcall expandFileName (const onSISTRING FILENAME); Function: Return to the full path of the file (including drive, path)
Parameters: filename: file name to handle
Example: ShowMessage (Application-> Exename); // Show your program file name, such as c: /mybcb/sample1.exe
(2 )ExtFileExt ()
Prototype: extern package anstruing __fastcall extractfileext (const onSition filename);
Function: Patting the extension from the file name
Parameters: FileName: The file name (full path) to process
Example: ShowMessage (extractFileExt (Application-> Exename)); // Display ".exe"
ExTractFileName ()
Prototype: Extern package anstruing __fastcall extractFileName (const onSition filename);
Function: Patting the file name without the path from the file name
Parameters: filename: file name to handle
Example: ShowMessage (ExtractFileExt ("c: //winnt//sol.exe")); // Display "Sol.exe"
⑷EXTRACTFILEPATH ()
Prototype: Extern package anstring __fastcall extractFilePath (const onSition filename);
Function: Patting the path name from the file name
Parameters: filename: file name to handle
Example: ShowMessage ("Winnt // Sol.exe")); // Displays "Winnt /"
⑸EXTRACTFILEDIR ()
Prototype: Extern package anstruing __fastcall extractfiledir (const onSistring filename);
Function: Patted the directory name from the file name (different from the previous function, excluding the last "/")
Parameters: filename: file name to handle
Example: ShowMessage ("WinntFileDir (" Winnt // Sol.exe ")); // Displays the difference between" Winnt ", pay attention to the previous function
⑹EXTRACTFILED ()
Prototype: Extern package Ansistring __fastcall extractfileDrive (const anstring filename);
Function: Extract the drive name from the file name
Parameters: filename: file name to handle
Example: ShowMessage (ExtractFileDrive ("c: //winnt//sol.exe"))); // Display "C:"
⑺Changefileext ()
Prototype: EXTERN PACKAGE SYSTEM :: ANSISTRING __FASTCALL CHANGEFILEXT (const system :: Ansistring filename, const system :: ansistring extension);
Function: Change the extension of the file name, not to rename the real file, just to process the file name this string: filename: The name of the file to be changed, Extension: new extension
Example: ShowMessage (CHANGEFILEXT ("C: //winnt//sol.exe", ".ooo")); // Displays "C: /Winnt/SOL.OOO"
⑻EXPANDUNCFILENAME ()
Prototype: extern package anstrunce __fastcall expanduncfilename (const onSISTRING FILENAME);
Function: Returns the full path of the file containing the network drive, the format is: // Machine name / shared name / file name
Parameters: filename: file name to handle
Example: ShowMessage (ExpanduncFileName ("f: //winnt//sol.exe")); / * If f: is a mapped network drive
// NT40 / WINNT, then "//nt40/winnt/sol.exe" *
⑼EXTRACTRELATIVEPATH ()
Prototype: Extern package Ansistring __fastcall extractrelativepath (const anstring basename);
Function: Patting relative path information from the file name, such as "../ss/ss.asd"
Parameters: BaseName: Benchmark file name; destname: target file name
example:
ShowMessage ("D: ///source///////////////ASM//dz.asm")); / * Display "../asm/dz.asm"* /
⑽EXTRACTSHORTPATHNAME ()
Prototype: Extern package anstrument __fastcall extractShortPathName (const onSswen);
Function: Convert file name to DOS 8, 3 format
Parameters: filename: file name to handle
Example: ShowMessage ("E: // Program files // Dual Wheel mouse // 4dmain.exe")); / * Display "E: /PROGRA ~ 1/Dualwh ~ 1/4dmain.exe" * /
⑾matchesmask ()
Prototype: Extern package bool __fastcall matchesmask (const onging filename, const anstring mask);
Function: Check if the file matches the specified file name format
Parameters: filename: The name of the file to be processed; Mask: File name format, support wildcard
Example: ShowMessage (Matchesmask ("lxf.exe", "*.? X?)); // Show" True "
-------------------------------------------------- ----------------------------
----
2, file management function
Such functions include setting and reading various operations related to the drive, subdirectories, and files, which lists the common functions of such operations and their functions. Function function
CreateDir () Creates a new subdirectory
Deletefile () Delete file
DirectoryExists () judgment if the directory exists
DiskFree () gets the residual space of disk
Disksize () Get disk capacity
FILEEXISTS () determines if the file exists
Filegetttr () Get file properties
FilegetDate () Get the date of file
GetCurrentDir () Get the current directory
RemoveDir () Delete Directory
SetCurrentDir () Sets the current directory
Let's introduce these functions below:
(1 )createdir ()
Prototype: Extern package bool __fastcall createdir (const system :: Ansistring Dir);
Function: Create a subdirectory, if you successfully return true, otherwise returning false
Parameters: Dir: The name of the subdirectory to be established
Example: Create ("ASM"); // Create a subdirectory called ASM in the current directory
(2) DELETEFILE ()
Prototype: extern package bool __fastcall deletefile (const system :: aNSISSTRING FILENAME);
Function: Delete files, return false if it successfully returns true, otherwise return false
Parameters: FileName: The file name to delete
Example: IF (OpenDialog1-> Execute ()) deletefile (OpenDialog1-> filename);
CA2Directoryexists ()
Prototype: Extern package bool __fastcall directoryexists (const system :: ansistring name);
Function: Check if the directory exists, if there is a returns, return false
Parameters: Name: Directory to be detected
Example: if (! Directoryexists ("ASM")) CreateDir ("ASM"); // If the ASM is not existed, it is created.
⑷diskfree ()
Prototype: Extern package __int64 __fastcall diskfree (byte driving); BYTE DRIVE
Function: Detect disk remaining space, return value in byte, if the specified disk is invalid, return -1
Parameters: drive: The code of the disk, 0 means the current disk, 1 = A, 2 = B, 3 = C Based on this class
Example: ShowMessage (DiskFree (0)); // Displays the remaining space of the current disk
⑸DISKSIZE ()
Prototype: extern package __int64 __fastcall disksize; Byte Drive
Function: Detect disk capacity, return value in byte, if the specified disk is invalid, return -1
Parameters: drive: The code of the disk, 0 means the current disk, 1 = A, 2 = B, 3 = C Based on this class
Example: ShowMessage (DiskFree (0)); // Displays the capacity of the current disk
⑹fileexists ()
Prototype: Extern package bool __fastcall fileexists (const onging filename);
Function: Detecting the file exists, if there is a return true, otherwise return false parameters: filename: the file name to be detected
Example: IF (FileExists ("aaa.asm")) deletefile ("aaa.asm");
⑺filegetttr ()
Prototype: extern package int __fastcall filegettttr (const anstruing filename);
Function: Get file properties, if an error returns -1
The return value is as follows, if returned $ 00000006 indicates a file with an implicit and system properties (4 2)
Constant value meaning
Fareadonly $ 00000001 Read-only file
FAHIDDEN $ 00000002 implied file
Fasysfile $ 00000004 System file
Favolumeid $ 00000008 Volume
Fadirectory $ 00000010 Directory
Faarchive $ 00000020 Archive file
Example: IF (Filegetttr ("LLL.TXT") & 0x2) ShowMessage ("This is a file with hidden properties");
There is a FileSetattr () corresponding to this, please refer to the help system
⑻filegetdate ()
Prototype: Extern package int __fastcall filegetdate (int Handle);
Function: Returns the number of seconds of the file to 0:00 pm at 0:00 to 1-1
Parameters: Handle: The file handle opened with fileOpen ().
example:
INT i = fileopen ("c: //autoexec.bat", fmopenread);
ShowMessage (FilegetDate (i));
FileClose (i);
There is filesetdate () corresponding to this, please contact the help system
⑼getcurrentdir ()
Prototype: extern package ansiString __fastcall getcurrentdir ();
Function: get the current directory name
Example: ShowMessage (getcurrentdir ());
⑽removedir ()
Prototype: Extern package bool __fastcall removedir (const anstring dir);
Function: Delete the directory, return false if you successfully returns true, otherwise return false
Parameters: Dir: Directory to delete
Example: IF (DIECTORYEXISTS ("ASM")) Removedir ("ASM");
⑾SETCURRENTDIR ()
Prototype: Extern package bool __fastcall setcurrentdir;
Function: Set the current directory, return false if you returned to true, otherwise returns false
Parameters: DIR: Directory name to switch to
Example: setcurrentdir ("c: // windows");
-------------------------------------------------- ----------------------------
----
3, file I / O function
Such functions complete the read and write related to the file, this type of operation and C based on I / O file operations, the following table lists the common functions of such operations and its functions.
FileOpen () Opens the file
FILECLOSE () Close file
FileRead () read file fileseek () file positioning
FileWrite () write files
FileCreate () creates a file
These functions are described in detail below.
(1) FileOpen ()
Prototype: Extern package int __fastcall fileopen (const anstring filename, int mode);
Function: Open the file, if you have returned its handle, or return -1
Parameters: FileName: The file name to open; mode: Opened mode, with the value as follows, "or" ("|") operator connection.
Constant value description
-------------------------------------------------- -----------
FmopenRead 0 opens read-only attributes
FMOpenWrite 1 Open only attribute
FmopenReadWrite 2 opens with read / write properties
FMShareCompat 0 is compatible with FCB mode (there is corresponding DOS function call in assembly, "Interesting self-contained information)
FMShareExClusive 16 sharing method: Open in exclusive way, before closing, others can't access
FMSharednywrite 32 Sharing Method: Refusing to write access
FMSharedenyRead 48 sharing method: refusing to read access
FMSharednynone 64 sharing method: unlimited, allow reading and writing
Example: int
i = fileopen ("c: //windows//win.ini", fmopenreadwrite | fmshareExClusive;
(2) FileClose ()
Prototype: Extern package void __fastcall fileclose (int Handle);
Function: Close the open handle.
Parameters: Handle: Handle to close
Example: FileClose (i);
CD, FileRead ()
Prototype: Extern package int __fastcall fileRead (int Handle, Void * Buffer, int COUN);
Function: Read the file, return the number of bytes actually read, and the handle must first be created by FileOpen or FileCreate.
Parameters: Handle: The handle to read; buffer: Saving the buffer of the read data; Count: Want to read the number of bytes
Example: Char Str [400]; FileRead (HND1, STR, 400);
⑷fileseek ()
Prototype: Extern package int __fastcall fileseek (int Handle, int offset, int origin);
Function: Mobile file read pointer, successfully returns the location of the file pointer, failed to return -1
Parameters: Handle: Associated handle; Offset: Moved; Orgin: Mobile Betmark, 0 = File Head, 1 = Current location, 2 = file end.
Example: ShowMessage (Fileseek (HND1, 0, 2)); // Get the length of the file
⑸filewrite ()
Prototype: Extern package int __fastcall filewrite (int Handle, Const Void * Buffer, INT Count);
Function: Write the file, return the number of bytes that actually written, the handle must first be created by FileOpen or FileCreate. Parameters: Handle: Handle to be written; buffer: Store buffer written in data; Count: Want to write bytes
Example: char str [] = "i love you"; FileWrite (HND1, STR, STRLEN (STR));
⑹filecreate ()
Prototype: extern package int __fastcall filecreate (const onSition filename);
Function: Create a file. Successfully returns its handle, otherwise returns -1
Parameters: filename: The name of the file to create
Example: if (! Fileexists ("kc.c")) HND1 = FileCreate ("kc.c");