MFC file operations, mfc files

Source: Internet
Author: User

MFC file operations, mfc files

File Operations: differences between binary files and text files. The binary file moves the data in the memory mode to the file, while the text file moves the asc code of the data to the file.
First, make a menu for reading and writing files and respond to
1. C method:
Fwrite:
Size: Item size in bytes number of bytes written each time
Count: Maximum number of items to be written, which is written several times in total.

FILE * p;
P = fopen ("c: // 1.txt"," w ");
Fwrite ("abc", 1, 4, p );
Fclose (p );
After opening the file, the file is mapped to the cache in the memory. All operations we do on the file are done in the memory. If we do not close the file, the changes made to files in the memory will not be reflected (saved) to the hard disk. Unless you close the current application, this operation will be automatically executed.
Fflush can empty the data in a stream (buffer zone) without closing the file. Here, the data in the buffer zone is output to the hard disk. In this way, you can write and output edges.
FILE * pFile = fopen ("c: // 1.txt"," w ");
Fwrite ("", 1, strlen (""), pFile );
// Fclose (pFile );
Fflush (pFile );
Fwrite ("how are you", 1, strlen (""), pFile );
Fflush (pFile );
Fclose (pFile );
We found that the next "h" is written after the last "heart" because the file has a pointer to the character position of the file, this pointer is a member of the char * _ ptr in the file structure. After we finish writing the word "heart", this pointer is behind the word "heart", so the next time we write "h", we write it behind the word "heart. If you want to output the second sentence before "dimension", move the position pointer of the file and use fseek
FILE * pFile = fopen ("c: // 1.txt"," w ");
Fwrite ("", 1, strlen (""), pFile );
// Fclose (pFile );
Fflush (pFile );
Fseek (pFile, 0, SEEK_SET );
Fwrite ("Beijing", 1, strlen ("Beijing"), pFile );
Fflush (pFile );
Fseek (pFile, 0, SEEK_END );
CString str;
Str. Format ("file size: % d", ftell (pFile ));
MessageBox (str );
Fclose (pFile );
Read files
FILE * pFile = fopen ("c: // 1.txt"," r ");
Char buf [100];
Fread (buf, 1,100, pFile); // although the read data exceeds the actual string length, find '/0' in the output'
MessageBox (buf );
Fclose (pFile );
Garbled characters appear because '/0' is not found in time during the output file. Change strlen of the file to sizeof.
When a file read/write function needs to read/write, it carries '/0'. It is similar to functions such as printf and strlen that end with'/0' as the function.
Garbled code can also be used
FILE * pFile = fopen ("c: // 1.txt"," r ");
Char buf [100];
Fseek (pFile, 0, SEEK_END );
Long len = ftell (pFile );
Rewind (pFile );
Fread (buf, 1, len, pFile );
Buf [len] = 0;
MessageBox (buf );
Fclose (pFile );
Method 3:
FILE * pFile = fopen ("c: // 1.txt"," r ");
Char buf [100];
Memset (buf, 0,100); // you can use any character to fill the memory block.
ZeroMemory (buf, 100); // The memory block can only be filled with the '/0' character.
Fread (buf, 1,100, pFile );
MessageBox (buf );
Fclose (pFile );
2. C ++: # include "fstream. h"
Write:
Ofstream ofs ("c: // 1.txt ");
Ofs. write ("", sizeof (" "));
Ofs. close (); // it is best to close the file by yourself. It is OK if it is not closed. The destructor of this filebuf object is closed for you.
Read:
Ifstream ifs ("c: // 1.txt ");
Char buf [100];
Ifs. read (buf, 100 );
MessageBox (buf );
When the code we write is changed
Ofstream ofs ("c: // 1.txt ");
Char str [3];
Str [0] = 'a ';
Str [1] = 10;
Str [2] = 'B ';
Ofs. write (str, sizeof (str ));
Ofs. seekp (0 );
Ofs. write ("china", sizeof ("china "));
It is found that the file size does not match when the file is written and read by text by default.
This is because when reading and writing a text file, all characters that encounter the asc Code of 10 will be converted. When writing a file, add the first 10 and the last 13 to the file, read the files 13 and 10 and replace these two characters with 10. note that do not convert the format to DOS when using ultraEdit.
This problem does not exist when reading and writing binary files (ios: binary. No conversion is performed.
In C ++, opening a file is completed in the constructor, and closing the file is completed in the destructor.
3. MFC method:
I. Write files:
CFile f ("c: // 1.txt", CFile: modeWrite | CFile: modeCreate );
F. Write ("hello", 5 );
A. The functions of several logos:
CFile: modeCreate: a new file is generated if no specified file exists. If yes, open the file and crop it to 0;
CFile: modeNoTruncate: When the file is opened, it is not cropped to 0;
B. Write Data to the end of the file:
CFile f ("c: // 1.txt", CFile: modeWrite | CFile: modeCreate |
CFile: modeNoTruncate );
F. SeekToEnd ();
F. Write ("hello", 5 );
// File. Close (); if I don't Close it, its destructor will Close for me.
II. Read files:
CFile f ("c: // 1.txt", CFile: modeRead );
Char buf [10];
Memset (buf, 0, 10 );
F. read (buf, 5 );
MessageBox (buf );
III. File Dialog Box:
Save dialog box:

CFileDialog fdlg (false );
// Fdlg. m_ofn.lpstrTitle = "why! ";
Fdlg. m_ofn.lpstrDefExt = "txt ";
Fdlg. m_ofn.lpstrFilter = "text file (*. txt)/0 *. txt/0 all files (*. *)/0 *. */0/0 ";
If (IDOK = fdlg. DoModal ())
{
// MessageBox (fdlg. GetFileName ());
CFile file (fdlg. GetFileName (), CFile: modeCreate | CFile: modeWrite );
File. Write ("", sizeof (" "));
File. Close ();
}

Open dialog box:

CFileDialog fdlg (true );
// Fdlg. m_ofn.lpstrTitle = "why! ";
Fdlg. m_ofn.lpstrFilter = "text file (*. txt)/0 *. txt/0 all files (*. *)/0 *. */0/0 ";
If (IDOK = fdlg. DoModal ())
{
CFile file (fdlg. GetFileName (), CFile: modeRead );
Char buf [100];
File. Read (buf, 100 );
MessageBox (buf );
}
2. Differences between text files and binary files:
A file is a special binary file. when it encounters a carriage return key 10, it will automatically add a 13 before it when writing the file, when a combination of 13 and 10 is encountered during file reading, it is restored to 10. The binary file is to write data into the file intact, and then read it out without the conversion of text files.
The following code demonstrates the difference:
When writing files:
Ofstream f ("c: // 1.txt ");
Char buf [3];
Buf [0] = 'a ';
Buf [1] = '/N ';
Buf [2] = 'B ';
F. write (buf, 3 );
When reading a file:
Ifstream f ("c: // 1.txt ");
F. setmode (filebuf: binary );
Char buf [5];
Memset (buf, 0, 5 );
F. read (buf, 5 );
CString str;
Str. Format ("% d, % d", buf [0], buf [1], buf [2], buf [3]);
MessageBox (str );
When writing a file, no format is specified. The file is stored in text format. The binary format is specified when the file is read. The data read is as follows:

If you comment out the f. setmode (filebuf: binary); Statement, the file will be read by text file, such:

2. Registry operations
1. Read and Write the win. ini file:
Use the GetProfileInt and WriteProfileString APIs to save the window size.
In the CMainFrame
Void CMainFrame: OnDestroy ()
{
CFrameWnd: OnDestroy ();

// TODO: Add your message handler code here
CRect rect;
GetWindowRect (& rect );
CString str;
Str. Format ("% d", rect. Width ());
WriteProfileString ("window size", "width", str );
Str. Format ("% d", rect. Height ());
WriteProfileString ("window size", "height", str );
}

In the CMainFrame
BOOL CMainFrame: PreCreateWindow (CREATESTRUCT & cs)
{
If (! CFrameWnd: PreCreateWindow (cs ))
Return FALSE;
// TODO: Modify the Window class or styles here by modifying
// The CREATESTRUCT cs
Cs. cx = GetProfileInt ("window size", "width", 100 );
Cs. cy = GetProfileInt ("window size", "height", 100 );
Return TRUE;
}

The GetProfileString of the API is used. For its fourth parameter lpReturnedString, a char * is required to return the result. Here, you cannot add a CString object to return the result. This is a special place. Other functions can be replaced by CString objects when char * is required.
Here we use the GetBuffer of CString to add this char *.
A CString object consists of a variable-length sequence of characters.
Because a String object consists of characters with variable length.

Returns a pointer to the internal character buffer for the CString object. The returned LPTSTR is not const and thus allows direct modification of CString contents.
Returns the pointer to the buffer (character array) of characters in a CString object. The returned pointer is not a constant pointer. Therefore, you can directly modify the content of the CString object pointed to by the pointer. This pointer is equivalent to the address of the CString internal character array.

If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CString member functions.
If you use the pointer returned by GetBuffer to change the content of the string, you must call ReleaseBuffer before using other CString member functions.

In InitInstance of CWinApp
CString str;
: GetProfileString ("window size", "height", "No value", str. GetBuffer (100), 100 );
AfxMessageBox (str );
The following tests WriteProfileString and GetProfileString of the CWinApp.
Description of WriteProfileString segments
· In Windows NT, the value is stored to a registry key.
· In Windows 3.x, the value is stored in the WIN. INI file.
· In Windows 95, the value is stored in a cached version of WIN. INI
In InitInstance of CWinApp
WriteProfileString ("favorites", "vc ++", "cainiao ");

CString str;
Str = GetProfileString ("favorites", "vc ++", "invalid value ");
AfxMessageBox (str );
Therefore, the content written here is written in HKEY_CURRENT_USER/Software/Local AppWizard-Generated Applications/MyFile/.

Implement a simple counter to limit the number of times the software is used:
SetRegistryKey (_ T ("myboleApp "));
Int x = GetProfileInt ("test", "times", 0 );
If (x> = 5)
Return false;
WriteProfileInt ("test", "times", ++ x );
CString str;
Str. Format ("You can also use % d Times", 5-x );
AfxMessageBox (str );

2. to read and write the WIN32 registry, perform the read and write operations on the registry from two menus. When writing, open the required operation key, that is, the return operation key handle uses RegCreateKey (this handle contains the primary key and subkey, the first parameter can be an opened handle or a predefined reserved handle value, you can create a new handle under the opened key according to the parameter of the opened handle and the rear face key, and then read and write according to the obtained handle.
When using RegSetValue for write operations, the write type must be REG_SZ. This type can be understood as a string ended with '/0'. If we want to write another data type, use RegSetValueEx.
The RegSetValue function sets the data for the default or unnamed value of a specified registry key. The data must be a text string.
The RegSetValue function sets data for the default registry key or a specified registry key without a name. The data must be a string.
RegSetValue the last parameter does not include '/0'
Use the new function to read and write data anywhere in the registry:
Write:
HKEY hKey;
RegCreateKey (HKEY_LOCAL_MACHINE, "software // favorites", & hKey );
// RegSetValue (hKey, NULL, REG_SZ, "WeiXin", 6 );
// RegSetValue (hKey, "course", REG_SZ, "WeiXin", 6 );
DWORD I = 100; // The following parameter requires an address, so this variable must be defined here.
RegSetValueEx (hKey, "JSP", NULL, REG_DWORD, (const byte *) & I, 4 );
RegCloseKey (hKey );
Read: in bytes

Read a default key value:
Char * buf;
Long len;
RegQueryValue (HKEY_LOCAL_MACHINE,
"Software // Why? // mylyhu // abc", NULL, & len );
Buf = new char [len];
RegQueryValue (HKEY_LOCAL_MACHINE,
"Software // Why? // mylyhu // abc", buf, & len );
MessageBox (buf );
Delete [] buf;

RegQueryValue parameter description:
If lpValue is NULL, and lpcbValue is non-NULL, the function returns ERROR_SUCCESS, and stores the size of the data, in bytes, in the variable pointed to by lpcbValue. this lets an application determine the best way to allocate a buffer for the value's data.
If the value of lpValue is NULL and the value of lpcbValue is not NULL, this function returns ERROR_SUCCESS, and the value of this variable indicates the size of the byte unit of the data, this allows an application to allocate space for the data of the query value in the best way.

Read the value of a key with a name.
HKEY hKey;
RegCreateKey (HKEY_LOCAL_MACHINE, "software // ", & hKey );
DWORD dwType;
DWORD data;
DWORD len = 4;
RegQueryValueEx (hKey, "JSP", NULL, & dwType, (BYTE *) & data, & len );
CString str;
Str. Format ("% d", data );
MessageBox (str );
: RegCloseKey (hKey );

Lock the registry:
HKEY hKey;
RegCreateKey (HKEY_CURRENT_USER, "software // microsoft // windows // currentversion // policies // system", & hKey );
DWORD x = 1;
RegSetValueEx (hKey, "DisableRegistryTools", 0, REG_DWORD, (const byte *) & x, 4 );
RegCloseKey (hKey );

Unregister
HKEY hKey;
RegCreateKey (HKEY_CURRENT_USER, "software // microsoft // windows // currentversion // policies // system", & hKey );
DWORD x = 0;
RegSetValueEx (hKey, "DisableRegistryTools", 0, REG_DWORD, (const byte *) & x, 4 );
RegCloseKey (hKey );

Push: http://www.cnblogs.com/roucheng/p/cppyiwei.html

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.