File read and write operations in MFC

Source: Internet
Author: User
Tags exception handling file permissions

How does the computer room manage the vast amount of information it holds? Windows Disk Management program provides us with a rigorous and efficient organization of information-the information on the hard disk is managed in the form of a file.

Storage-oriented file technology

What is a file. In a computer, an article, a picture, a program, and so on, are stored on disk in the form of files, each with a file name. A computer is an access to a file by name. The file name is formatted as follows: the primary filename. extension. Why do you use files in your program?

Typically, data in a program is purged from memory after the program is run, and the program does not appear automatically when it is run again. In the process of programming will inevitably encounter the problem of the permanent preservation of some data, when the program is closed, still can use the data, then need to do file operations. File Type

The files processed by Visual C + + usually fall into two categories:

Text file: ASCII text can only be read by any text editor.

Binary files:

Refers to a general designation of a file that contains any format or unformatted data.

Here only the text file read and write, INI file belongs to the category of text file, and the structure and use of INI file is different from ordinary text file, so will be introduced separately. Part I: Text files reading and writing of text files

Recognize the CFile class, understand the text file, the correct and flexible application of text file access information, avoid the common misunderstanding of text file reading and writing.

CFile is a basic class of MFC file operations that directly supports buffer-free binary disk I/O operations and supports text files, memory files, and socket files through its derived classes. Customer Action Record instance function preview and key knowledge points

Many systems, for security or other reasons, often require the keyboard to be monitored at any time, and applications written using hook technology can do this well. The software has produced a customer operation record software, that is, in the software running process, the user on the keyboard key operation will be recorded, so the maintenance of the normal operation of the software is very beneficial.

As long as the customer action recording software is started, the key will be recorded regardless of whether the input focus is on the software. We need the keyboard system monitoring, as long as the software is running, regardless of what the current computer is doing, can monitor the behavior of the user button and respond, this will use the hook technology.

Hook technology is widely used in many special software, such as PowerWord "Take word" function, use the hook meter technology.

The essence of a hook is a program that handles system messages and hangs them into the system through system calls. There are many kinds of hooks, each hook can intercept and process the corresponding message, whenever a specific message issued, before reaching the destination window, the hook program to intercept the message, get control of the message. In this case, the intercepted message can be processed in the hook function, and it can even force the end of the message to be passed.

From the nature of the hook, you can first intercept the operating system of various messages to process, so it is almost omnipotent, because Windows applications are based on message-driven, application operations are dependent on the type of messages it gets and the content.

If the hook process is implemented in the application, the hook is padded if the application is not the current window, and if the hook is implemented in the DLL, the program dynamically invokes it in the runtime, which can monitor the system in real time. As needed, we used the way to implement hooks in a DLL.

(Application EXE?) The difference between the DLL and the text file storage Management

Characters are processed by the computer in the form of binary code, that is, a character corresponds to a 8-bit binary number, the set of binary code is called ASCII code.

The basic ASCII code has 128, the highest digit is 0, and the corresponding decimal number is 0-127. Characters on the keyboard, such as English letters, numbers, and some common symbols, use the basic ASCII section. For example, the ASCII code of the number "0" is represented by a binary number of 00110000 (that is, decimal number 48).

The extended ASCII code has 128, the highest bit is 1, and the corresponding decimal number is 128-255. Some tabs and other symbols use the extended ASCII code section.

In order to solve the problem of storing and displaying Chinese characters, our country has developed international GB2312. According to the stipulation, a Chinese character is composed of 2 extended ASCII codes, this high order of 1 Double byte encoding is the Chinese character's internal code, short for the inner code. For example, the Chinese character "learning" in the machine code in binary notation is 11010001 10100111 (that is, the decimal number 206 and 167), in decimal notation is 53671 (206*256+167). For characters, the text file stores its ASCII code, and for Chinese characters, the text file stores its inner code, which is two-bit ASCII, such as the string "0 learns 0", and the content stored in the text file is 00110000 11010001 10100111 00110000 Correct text file read and write process

1. define file variables; 2. Open the specified file; 3. To write information from a text file; 4. Read information from a text file; 5. close file 1, define file variables

Define file Variable format: CStdioFile file variable;

For example, define a file variable named F1, with the following statement: CStdioFile F1;

2. Open the specified file

You can open the disk file directly through the CStdioFile constructor, and you can specify the open mode (read only, write only, read and write, and so on) with the flag bit:

CStdioFile (LPCTSTR lpszfilename,uint nopenflags);

Where lpszFileName represents the name of the file to open, which can be a relative or absolute path

Nopenflags set the file open as a flag, you can specify a "|" Connect multiple flag bits. The following are common open flags:

Cfile::typetext: Opening a file as a text file

Cfile::typebinary: Opening a file as a binary file

Cfile::modecreate: If the file with the specified filename does not exist, create a new file, or empty the file if the file exists and the CFILE::MODENOTRUNCATE flag is not set.

Cfile::modenotruncate: If the file exists, do not delete its length to 0 (that is, do not empty the data in the file).

Cfile::moderead: Open File as read-only

Cfile::modereadwrite: Open a file in a readable and writable way

Cfile::modewrite: Open File as Write-only

Cfile::sharedenynone: No other processes are allowed to read and write files after the file is opened

Cfile::shareexclusive: Prevents other processes from reading and writing to files after the file is opened

Cfile::sharedenyread: Prevents other processes from reading the file after the file is opened

Cfile::sharedenywrite: Prevents other processes from writing to files after the file is opened

In addition, you can open the file in the constructor instead of simply calling the empty constructor Cstidofile () and then opening the file with Cstdiofile::open (). The first two and non-null constructors of the open function have the same arguments, and their declarations are as follows:

BOOL Open (LPCTSTR lpszfilename,uint nopenflags,cfileexception* perror=null);

The 3rd parameter is related to exception handling when an open failure occurs. Example 1: Open a file as read-only

Steps:

Use AppWizard to create a dialog application, delete all of its automatically generated controls, and add a button control. Double-click the control to add code to the appropriate function:

char * pszfilename= "c://myfile.txt";
CStdioFile MyFile;
CFileException fileexception;
if (!myfile.open (pszfilename,cfile::modecreate| Cfile::typetext| Cfile::moderead), &fileexception
{
    TRACE ("Can ' t Open file%s, error =%u/n", pszfilename,fileexception.m_ cause);
}

Run Result: If there is no MyFile.txt file under c:/, the new file will be reborn. 3. To write information from a text file

CStdioFile provides a function writestring to write text to a text file, and the WriteString function is formatted as follows:

void WriteString (LPCTSTR lpsz);

The WriteString parameter lpsz is a string ending with a "/0" character that writes the contents of this string to the file.

tip : When you use the WriteString function, if you want the contents of the text file to be wrapped once for each writestring, you need to output "/n" where you want to wrap the line:

Myfile.writestring ("line 1th/n"); Instance 2: Writing text to a file

Create MFC based dialog box program, delete all automatically added controls, add a "OK" button, double-click the button, press the default Add Event function, double-click the button, add the following code at the corresponding function:

char* pszfilename= "C://myfile.txt";
CStdioFile MyFile;
CFileException fileexception;
if (Myfile.open (pszfilename,cfile::typetext| cfile::modecreate| Cfile::modereadwrite), &fileexception)
{
    myfile.writestring ("The 1th Line/n");
    CString Strorder;
    Strorder.format ("%d,%.3f", 66,88.88);
    Myfile.writestring (Strorder);
}
else
{
    TRACE ("Can ' t Open file%s,error=%u/n", pszfilename,fileexception.m_cause);
}

Program Run Result: C:/myfile.txt file contains the following:

Line 1th

66,88.880 4. Reading information from a text file

Cstidofile provides a function readstring to read text, readstring in two forms:

Virtual LPTSTR ReadString (LPTSTR lpsz, Uinit Nmax);

The parameters for the ReadString function are as follows:

Lpsz: is a user-supplied pointer to a string that accepts text read from a file and ends with "/0".

Nmax is the number of text characters that are allowed to be read this time, regardless of the "/0" character, which means that you can read up to nMax-1 text characters.

The return value of the readstring is a pointer to a LPTSTR type that points to a text string read from the file and returns null if the end of the file is reached.

Another form of ReadString is:

BOOL ReadString (cstring& rstring);

The parameter rstring is used to hold text that is read from a file.

The CString version ignores carriage return line breaks, and the return value is a Boolean value. If the return value is False, it indicates that no characters were read because the end of the file was reached.

tip: Every time you perform a readstring, a row of data is automatically read from the text file, and the file action pointer automatically jumps to the next line. Example 3: Reading text information from a file

Step: Create an MFC program based on the dialog box, delete all automatically added controls, Add button controls, add events to the button, and at the appropriate function, add the following code:

char* pszfilename= "C://myfile.txt";
CStdioFile MyFile;
CFileException fileexception;
if (Myfile.open (pszfilename,cfile::typetext| Cfile::modereadwrite), &fileexception)
{
    myfile.seektobegin ();
    CString str1;
    Myfile.readstring (STR1);
    CString str2;
    Myfile.readstring (STR2);
    AfxMessageBox (STR1+STR2);
}
else
{
    TRACE ("Can ' t Open file%s,error=%u/n", pszfilename,fileexception.m_cause);
}
Myfile.close ();

Program run Result: Set breakpoints for program F9, and then F5 step, the result is as follows:

5. Close the file

When the operation of the file is complete, use CloseFile to close the file.

Function Cstdiofile::close closes a file, usually a file should be closed when it is used:

Myfile.close ();
wrong text file read and write process

The most common mistake when reading and writing a text file is---the action file does not exist. Typical reasons for this error are: 1. Path Error

char * pszfilename= "c://windows//myfile.txt";
CStdioFile MyFile;
CFileException fileexception;
if (!myfile.open (pszfilename,cfile::modecreate| Cfile::typetext| Cfile::modereadwrite), &fileexception)
{
    //File action code
}
else
{
    TRACE ("Can" T Open file%s, Error =%u/n ", pszfilename,fileexception.m_cause);
}
Myfile.close ();

Because the file variable is associated with the filename of an absolute path, and the program's data is usually stored in a relative path, an error occurs when the relative and relative paths are inconsistent.

For example, the previous program was meant to read a row of data from the MyTextFile.txt file under the Windows installation directory, but if the operating system installation path is not C:/windwos but c:/winnt, then the program will go wrong.

The solution is to use a relative path in the program, and the correct procedure is as follows:

Get Windows path
LPTSTR lpbuffer=new Char[max_path];:
: GetWindowsDirectory (lpbuffer,max_path);
strcat (lpbuffer, "//myfile.txt");
CStdioFile MyFile;
CFileException fileexception;
if (Myfile.open (lpbuffer,cfile::typetext| cfile::modecreate| Cfile::modereadwrite), &fileexception)
{
    //File action code
}
else
{
    TRACE (' Can ' t open file%s , error =%u/n ", pszfilename,fileexception.m_cause);
}
CString strfiletitle= "MyFile.txt";
CStdioFile MyFile;
CFileException fileexception;
if (Myfile.open (strfiletitle,cfile::typetext| Cfile::modereadwrite), &fileexception)
{
    //File Operation code
    myfile.writestring ("Test.") ");
}
else
{
    TRACE ("Can ' t Open file%s, error =%u/n", pszfilename,fileexception.m_cause);
}
Myfile.close ();
2. Operation file does not exist

If the MyFile.txt file does not exist under all the paths of the application, an error occurs when the WriteString writes the information.

The workaround is to check that the file exists before opening the file in the program. The following procedure:

CString strfiletitle= "MyFile.txt";
CFileFind Finder;
if (finder. FindFile (strfiletitle))
{
    CStdioFile myFile;
    CFileException fileexception;
    if (Myfile.open (lpbuffer,cfile::typetext| cfile::modecreate| Cfile::modereadwrite), &fileexception)
    {
        //File action code
    }
    else
    {
        TRACE (' Can ' t open file%s , error =%u/n ", pszfilename,fileexception.m_cause);
    }
else
{
    TRACE ("Can ' t find file%s/n", strfiletitle);
}
Myfile.close ();
3. Go beyond file permissions for read and write operations

When you open a file, you specify a file's read and write permissions through parameters, and an error occurs if the read-write operation does not correspond to the corresponding permissions.

The following procedure is a typical example of ignoring file manipulation permissions:

CString strfiletitle= "MyFile.txt";
CStdioFile MyFile;
CFileException fileexception;
if (Myfile.open (strfiletitle,cfile::typetext| cfile::modecreate| cfile::notruncate| Cfile::moderead), &fileexception)
{
    //File Operation code
    myfile.writestring ("Test!");
}
else
{
    TRACE ("Can ' t Open file%s,error=%u/n", strfiletitle,fileexception.m_cause);
}
Myfile.close ();
The weapon of the Child: 1. Accurate location of the file path

In the process of manipulating a file, you often need to place the text file in the directory of the program itself, but if you use a relative path in your program that does not specify any path information, such as:

Myfile.open ("MyFile.txt", cfile::modecreate| Cfile::typetext| Cfile::modereadwrite);

Then there is the possibility of a situation that is not properly positioned, and the exact location of the file is obtained by obtaining an absolute path to the executable program itself, such as:

TCHAR Filepath[max_path];
GetModuleFileName (Null,filepath,max_path);
(_TCSTCHR (FilePath, '//") [1]=0;
Lstrcat (filepath,_t ("MyFile.txt"));
CStdioFile MyFile;
CFileException fileexception;
if (Myfile.open (filepath,cfile::modecreate| Cfile::typetext| Cfile::modereadwrite), &fileexception)
{
    //File action code
}
else
{
    TRACE (' Can ' t open file%s , error=%u/n ", filepath,fileexception.m_cause);
}
Myfile.close ();
2. Read the line specified by the text file and get the total number of rows in the text file.

Reads a line specified by a text file and gets the total number of rows in the text file

To count the total number of rows in a text file, you can read from scratch, until the end of the file, the program:

CStdioFile MyFile;
CFileException fileexception;
if (Myfile.open ("MyFile.txt", cfile::modecreate| cfile::modenotruncate| Cfile::typetext| Cfile::modereadwrite), &fileexception)
{
    CString strcontent;
    int order=1;
    while (Myfile.readstring (strcontent))
    {
        if (2==order)
        {
            AfxMessageBox (strcontent);
        }
        Order=order+1
    }
}
else
{
    TRACE ("Can ' t Open file");
}
Myfile.close ();
Instance Demo file operation procedure Customer Action Record instance

The software is divided into two parts, part of the DLL module, which uses hook technology to complete the keyboard monitoring and writing file functions; the other part is the interface section, which invokes the DLL to start and stop the Customer action logging feature.

1th Step: Create an MFC DLL project

Step 2nd: Create a TestHook.h file

3rd Step: Join a global shared data variable

Step 4th: Save the DLL instance handle

Step 5th: Member functions of Class Ckeyboradhook

6th step: Create hooks to execute the program step 1th: Create an MFC DLL project

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.