MFC file Operations

Source: Internet
Author: User
Tags fread

File operations: The difference between binary and text files. The binary file moves the data in-memory mode to the file intact, and the text file is the ASC code that moves the data to the file.
Start by making a menu that reads and writes files and responds in Cxxview
1. C in the way:
Fwrite
Size:item size in bytes number of bytes per write
Count:maximum number of items to be written, written a few times.

FILE *p;
P=fopen ("C://1.txt", "w");
Fwrite ("abc", 1,4,P);
Fclose (P);
Since we open the file and the file is mapped to the in-memory cache, the action we do on the file is done in memory, and if we do not close the file, the changes made to the file in memory will not be reflected (saved) to the hard disk, unless you close the current application, which will automatically perform the file close operation.
Fflush can empty the data in a stream (buffer) when the file is not closed, where the erase is to output the buffer data to the hard disk. This can achieve the effect of the side write side output.
file* Pfile=fopen ("C://1.txt", "w");
Fwrite ("How to ask the Net", 1,strlen ("Ask the Net"), PFile);
Fclose (PFile);
Fflush (PFile);
Fwrite ("How is You", 1,strlen ("Q-Net"), PFile);
Fflush (PFile);
Fclose (PFile);
We find that the next "H" is written in the Last "heart", because, for the file it has a pointer to a file character position, this pointer is different from the file pointer, is the file structure of this char *_ptr; When we finish writing the word "heart", the pointer is in the "heart" after the word, so the next time you write "H" at the back of the "heart" write. If you want to output the second sentence in front of the "dimension", move the position pointer of the file, using the Fseek
file* Pfile=fopen ("C://1.txt", "w");
Fwrite ("How to ask the Net", 1,strlen ("Ask the Net"), 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 the file
file* Pfile=fopen ("C://1.txt", "R");
Char buf[100];
Fread (buf,1,100,pfile);//Although the read data exceeds the length of the actual string, the output is still looking for '/0 '
MessageBox (BUF);
Fclose (PFile);
Garbled, because the output file is not in time to find '/0 '. Change the strlen of the write file to sizeof
File read and write functions need to read and write the '/0 ' band, it is similar to printf and strlen functions such as "/0" as a function end representation.
Garbled solution 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);
The third method:
file* Pfile=fopen ("C://1.txt", "R");
Char buf[100];
memset (buf,0,100);//You can fill this memory block with any character.
ZeroMemory (buf,100);//Use only '/0 ' characters to populate this memory block.
Fread (Buf,1,100,pfile);
MessageBox (BUF);
Fclose (PFile);
2. C + + way: #include "fstream.h"
Write:
Ofstream ofs ("C://1.txt");
Ofs.write ("How to ask the Net", sizeof ("How to ask the Net"));
Ofs.close ();//It is best to shut down the file yourself, but the destructor for this Filebuf object is off.
Read:
Ifstream ifs ("C://1.txt");
Char buf[100];
Ifs.read (buf,100);
MessageBox (BUF);
When we write the code to change to
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 text is written and read by default.
This is because when the text file read and write, encountered the ASC code of 10 characters, will be converted, write the file will be 10 before adding 13 to the file, read the file read 13 and 10, the two characters into a 10. Note Do not turn into DOS format when using UltraEdit.
This problem does not exist if you read and write to a binary file (ios::binary). Do not make any conversions.
C + + file operations The open file is done in the constructor, and closing the file is done in a destructor.
3. MFC's Way:
I. Write files:
CFile f ("C://1.txt", cfile::modewrite| Cfile::modecreate);
F.write ("Hello", 5);
A. The role of several symbols:
Cfile::modecreate: Create a new file without the specified file, open the file, and crop it to 0;
Cfile::modenotruncate: Do not crop to 0 when opening the file;
B. Write the 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, the destructor will close for me.
II. Read the file:
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 ask to build!" ";
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 ("How to ask the Net", sizeof ("How to ask the Net"));
File. Close ();
}

Open the dialog box:

CFileDialog Fdlg (TRUE);
Fdlg.m_ofn.lpstrtitle= "Why ask to build!" ";
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. The difference between a text file and a binary file:
A file file is a special binary file that, when it encounters a return key of 10 o'clock, automatically adds a 13 to the file when it is written, and then restores the file to 10 when it encounters a combination of 13 10. and the binary file is to write the data intact, and then read it intact, no text file of this conversion operation.
The following code demonstrates this difference:
When writing to a file:
Ofstream f ("C://1.txt");
Char buf[3];
Buf[0]= ' a ';
buf[1]= '/n ';
Buf[2]= ' B ';
F.write (buf,3);
When the file is read:
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,%d,%d", buf[0],buf[1],buf[2],buf[3]);
MessageBox (str);
When writing to a file without specifying a format, the file is stored in text format, when the file is read out, the binary format is specified, and the data is read as:

If the comment f.setmode (filebuf::binary); statement, the file will be read as a text file, such as:

Second, the operation of the registry
1. Read-Write Win.ini file:
Use the API's Getprofileint and writeprofilestring to implement a save window size example.
In CMainFrame's
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 CMainFrame's
BOOL CMainFrame::P Recreatewindow (createstruct& CS)
{
if (! CFrameWnd::P Recreatewindow (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;
}

Demonstrates the use of the GetProfileString API. For its fourth parameter lpreturnedstring need to add a char* to return. It is not possible to add CString objects to return, which is a special place. Other functions are generally char* and can be replaced with CString objects.
Here we use CString's GetBuffer to add this char*.
A CString object consists of a variable-length sequence of characters.
Because a string object consists of a sequence of variable-length characters.

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.
A pointer to a buffer (character array) that returns an internal character of an CString object, which is not a pointer to a constant, allowing direct modification of the contents of the CString object pointed to by the pointer. This pointer is equal 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 O Ther CString member functions.
If you change the contents of the string using the pointer returned by GetBuffer, you must call ReleaseBuffer before you use the CString other member function.

In the InitInstance of CWinApp.
CString str;
:: GetProfileString ("Window Size", "height", "No value", str.) GetBuffer (100), 100);
AfxMessageBox (str);
Test the CWinApp writeprofilestring,getprofilestring below.
For writeprofilestring There is a paragraph description
· In Windows NT, the value was stored to a registry key.
· In Windows 3.x, the value was stored in the WIN. INI file.
· In Windows-stored, the value is a cached version of WIN. Ini
In the InitInstance of CWinApp.
WriteProfileString ("collection", "VC + +", "rookie");

CString str;
Str=getprofilestring ("collection", "VC + +", "Invalid value");
AfxMessageBox (str);
So the words written here are written in the hkey_current_user/software/local appwizard-generated applications/myfile/restoration.

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. Read and write the WIN32 registry, do two menus to read and write the registry, write the first time to open the key to operate, that is, return the operation of the key handle with RegCreateKey (the handle contains the primary key and the subkey, the first argument can be an open handle or a predefined reserved handle value, In the case of the previously opened handle, you can create a new handle under the open key, based on the argument of the open handle and the following subkey, and then read and write according to the handle.
When writing with RegSetValue, the type must be REG_SZ, which can be interpreted as a string ending with '/0 ', and 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 is a text string. The
RegSetValue function sets the data for the default or the specified registry key without a name, which must be a string.
RegSetValue The last parameter does not include '/0 '
to read and write anywhere in the registry using the new function:
Write:
HKEY HKEY;
RegCreateKey (HKEY_LOCAL_MACHINE, "software//Collection", &hkey);
//regsetvalue (HKEY,NULL,REG_SZ, "Weixin", 6);
//regsetvalue (HKey, "course", REG_SZ, "Weixin", 6);
DWORD i=100;//The following parameter is the address, so define this variable
RegSetValueEx (HKey, "JSP", Null,reg_dword, (CONST byte*) &i,4);
RegCloseKey (HKey);
Read: In bytes in bytes

Read the value of a default key:
Char *buf;
Long Len;
RegQueryValue (HKEY_LOCAL_MACHINE,
"software//Q-Net//mylyhu//abc", Null,&len);
Buf=new Char[len];
RegQueryValue (HKEY_LOCAL_MACHINE,
"software//Q-Net//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 store The size of the data, in bytes, and the variable pointed to by Lpcbvalue. This lets an application determine the best means to allocate a buffer for the value ' s data. 
If Lpvalue is null and LPCBV Alue is not NULL, this function returns ERROR_SUCCESS and stores the size of the byte units of the data by lpcbvalue the pointer to the variable, which is the best way for an application to allocate space for the data of the queried value

Read the value of a key with a name.
HKEY HKEY;
RegCreateKey (HKEY_LOCAL_MACHINE, "software//Restoration", &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 Registration Table:
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);

To solve the registration form
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

MFC file Operations

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.