CFile Read and write files (solve Chinese characters, newline, empty character problems).

Source: Internet
Author: User
CStdioFile file;
if (!file. Open (_t ("D:\\file.txt"), Cfile::modereadwrite)
{
File. Open (_t ("D:\\file.txt"), cfile::modecreate| Cfile::modereadwrite);
}
CString str;
CTime Time=ctime::getcurrenttime ();
Str. Format (_t ("%d-%-d-%-d%d:%-d:%-d Record:"), time. GetYear (), time. GetMonth (), time. Getday (), time. Gethour (), time. Getminute (), time. Getsecond ());
The STR string ends with a str.getlenth, which means the last byte is not displayed but exists, and the last one is not.
WORD Num=widechartomultibyte (Cp_acp,null,str,-1,null,0,null,false);
Char *p=new Char[num];
memset (P,0,num);
WideCharToMultiByte (Cp_acp,null,str,-1,p,num,null,false);
File. Write (P,strlen (p));
File. Seektoend ();
File. Write ("\ n", 1);//a newline character \ n, the ASCI code used when writing, the newline in a byte; but when read, File.getlenth () interprets the newline as two bytes;
File. Seektoend ();
File. Write ("Good", strlen ("good"));
File. Close ();

if (!file. Open (_t ("D:\\file.txt"), Cfile::modereadwrite)
{
File. Open (_t ("D:\\file.txt"), cfile::modecreate| Cfile::modereadwrite);
}
Char *q;
Q=new Char[file. GetLength () +1];
memset (Q,0,file. GetLength () +1);
File. Read (Q,file. GetLength ()); the second parameter of//read stipulates that the carriage return line is a character, and when filling in the first parameter of read, fill in the byte of a char[] in a newline;
CString A (q);
Delete q;
MessageBox (a);
File. Close ();

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.