write CString to file by Adrian
Adrian
Wed Jul 30 07:47:33 CDT 2003
OK, I see this message board is treating the static_cast
syntax as though it contains an HTML tag, which it is
stripping out, therefore when I post
static_cast lessthan const char* greaterthan (message)
(replace lessthan and greaterthan with the appropriate
symbols) it is appearing as
static_cast(message)
Doh!
>-----Original Message-----
>One other problem that has not been mentioned is here:
>
>text = (char*)message.GetBuffer(sizeof(text));
>
>sizeof(text) returns the sizeof of text data type, i.e.,
a
>pointer; all pointers in 32 bit land are 4 bytes. So
>you're getting a 4 byte buffer. This should be
>
>text = (char*)message.GetBuffer(message.GetLength());
>
>The problem with static_cast is because the syntax is
>
>static_cast<const char*>(message)
>
>i.e.,
>
>//Example A:
>
>void Test::WriteLog(const char* path, const CString&
>message)
>{
> FILE* fp = fopen(path, "a");
> fprintf(fp, "\n%s", static_cast<const char*>(message));
> fclose(fp);
>}
>
>I would prefer to write the function like this:
>
>//Example B:
>
>void Test::WriteLog(const char* path, const char* message)
>{
> FILE* fp = fopen(path, "a");
> fprintf(fp, "\n%s", message);
> fclose(fp);
>}
>
>This uses the CString LPCTSTR operator (e.g., const char*)
>and has the advantages over example A. When you call
>Example A WriteLog with a literal string, e.g.,
>
>WriteLog("c:\\temp\\temp.log", "Hello");
>
>a CString message object has to be created (memory
>allocated). With Example B no object is created, as the
>compiler just passes a pointer to the literal. This is
>more efficient, particularly if you are doing a lot of
>logging.
>
>When you call Example A with a CString object, e.g.,
>
>CString sTemp("Hello");
>WriteLog("c:\\temp\\temp.log", sHello);
>
>because message is a reference, only a pointer is passed.
>With Example B, the CString operator LPCTSTR returns the
>internal CString pointer to the string data. Either way
is
>equally as efficient.
>
>For this reason I avoid CString& for function parameters.
>
>After all that, in MFC you should be using CStdioFile.
>
>
>
>>-----Original Message-----
>>Hello,
>>
>>I've a problem writing a CString to file.
>>I first convert to char* but it does not seem to work.
>>The code is below ...
>>
>>Bob
>>
>>
>>void Test::WriteLog(char* path,CString message)
>>{
>>char* text = new char[1024];
>>text = (char*)message.GetBuffer(sizeof(text));
>>FILE* fp = fopen(path,"a");
>>fprintf(fp,"\n%c",text);
>>fclose(fp);
>>delete text;
>>}