CFileDialog drives me insane. Handle Problem ?

Hi,
i want to communicate some strange Problems i have with CFileDialog.
Hope someone can push in the right direction.

1. Problem:

	CFileDialog FileDlg(true);

	INT_PTR nResponse = FileDlg.DoModal();

	if (nResponse == IDOK){}else{return;}

	LPSTR file = FileDlg.GetFileName().GetBuffer();
	LPSTR folderPath = FileDlg.GetPathName().GetBuffer();

	ULONGLONG fSize = GetFileSizeInByte(fileUrl.GetBuffer());

long GetFileSizeInByte(const char* sFileName)
{
  std::ifstream f;
  f.open(sFileName, std::ios_base::binary | std::ios_base::in);
  if (f.eof()) { return 0; }
  if (!f.good()) { return -1; }
  if (!f.is_open()) { return -2; }
  f.seekg(0, std::ios_base::beg);
  std::ifstream::pos_type begin_pos = f.tellg();
  f.seekg(0, std::ios_base::end);
  return static_cast<long>(f.tellg() - begin_pos);
}

fSize is in 80% of cases '-1'. In 15% '-2'. Sometimes it works as
expected.
If i set 'folderPath ' to a stistc value and dont call
FileDlg.DoModal(); all works 100% correct.

2. Problem:
I have some customized Sub-Dialogs (With GUI-Buttons, Custom-Bkg). All
works correct until i call CFileDialog::DoModal()  /
GetOpenFileDialog() with return IDOK (means if i choose a File an Click
Ok, OnCancel the Problem does'nt occur). If i do so and after that call
my Subdialog, it is completely destroyed. All the GUI Buttons are not
Visible and not all of them are clickable. The Background is gone and
just some weird rectangels are visible (a mixture of grey rect's and
the underlaying bckg).
If i call a Java FIleOpenDialog via JNI out of this app instead of
CFileDialog, all works as expected.

Some Ideas ?
Does someone know another imlementation of a FileDialog ?

best regards,
David

0
dawjdh (9)
11/13/2006 10:18:57 AM
vc.mfc 33608 articles. 0 followers. Follow

9 Replies
825 Views

Similar Articles

[PageSpeed] 4

>1. Problem:
>
>	CFileDialog FileDlg(true);
>
>	INT_PTR nResponse = FileDlg.DoModal();
>
>	if (nResponse == IDOK){}else{return;}
>
>	LPSTR file = FileDlg.GetFileName().GetBuffer();
>	LPSTR folderPath = FileDlg.GetPathName().GetBuffer();
>
>	ULONGLONG fSize = GetFileSizeInByte(fileUrl.GetBuffer());

What is fileURL ?

>long GetFileSizeInByte(const char* sFileName)

Why not just use the GetFileSize API?

Dave
0
davidl7375 (2060)
11/13/2006 10:34:25 AM
Oh, Sorry:

	CString fileUrl;
	fileUrl.Format("%s",folderPath);

I try'd  several  way's to get the fileSize:


 /* #### Variante 1 ####*/
long GetFileSizeInByte(char *fileName){

         long sz = -1;
        FILE* f;

        f = fopen (fileName, "rb");
        if (f)
        {
            fseek (f, 0, SEEK_END);
            sz = ftell (f);
            fclose (f);
        }

	return sz;
}
 /* #### Variante 2 ####*/
long GetFileSizeInByte(const char* sFileName){

  std::ifstream f;
  f.open(sFileName, std::ios_base::binary | std::ios_base::in);
  if (f.eof()) { return 0; }
  //if (!f.good()) { return -1; }
  if (!f.is_open()) { return -2; }
  f.seekg(0, std::ios_base::beg);
  std::ifstream::pos_type begin_pos = f.tellg();
  f.seekg(0, std::ios_base::end);
  return static_cast<long>(f.tellg() - begin_pos);

}
 /* #### Variante 3 ####*/
long GetFileSizeInByte( const char * szFileName )
{
  struct __stat64 fileStat;
  int err = _stat64( szFileName, &fileStat );
  if (0 != err) return 0;
  return (long)fileStat.st_size;
}
 /* #### Variante 4 ####*/
long GetFileSizeInByte( const char * szFileName )
{
  struct stat fileStat;
  int err = stat( szFileName, &fileStat );
  if (0 != err) return 0;
  AfxMessageBox(fileStat.st_size);
  return (long)fileStat.st_size;
}

Thats all ok, the Problem is the FileOpenDialog, when i do
GetFileSizeInByte( const char * szFileName ) with a static parameter it
works in all Variants but not if i first call that Dialog.

> Why not just use the GetFileSize API?

So why would you recommend me to use the GetFileSize API instead of
other's ?

best Regards,
David

David Lowndes schrieb:

> >1. Problem:
> >
> >	CFileDialog FileDlg(true);
> >
> >	INT_PTR nResponse = FileDlg.DoModal();
> >
> >	if (nResponse == IDOK){}else{return;}
> >
> >	LPSTR file = FileDlg.GetFileName().GetBuffer();
> >	LPSTR folderPath = FileDlg.GetPathName().GetBuffer();
> >
> >	ULONGLONG fSize = GetFileSizeInByte(fileUrl.GetBuffer());
>
> What is fileURL ?
>
> >long GetFileSizeInByte(const char* sFileName)
> 
> Why not just use the GetFileSize API?
> 
> Dave

0
dawjdh (9)
11/13/2006 10:54:33 AM
See below...
On 13 Nov 2006 02:18:57 -0800, "dawjdh@googlemail.com" <dawjdh@googlemail.com> wrote:

>Hi,
>i want to communicate some strange Problems i have with CFileDialog.
>Hope someone can push in the right direction.
>
>1. Problem:
>
>	CFileDialog FileDlg(true);
>
>	INT_PTR nResponse = FileDlg.DoModal();
>
>	if (nResponse == IDOK){}else{return;}
****
AVOID ALL TENDENCIES TO WRITE COMPLEX CODE IN A SINGLE LINE!
	if(nResponse != IDOK)
                       return;
is VASTLY SIMPLER, EASIER TO READ, AND EASIER TO UNDERSTAND
****
>
>	LPSTR file = FileDlg.GetFileName().GetBuffer();
****
This cannot possibly work, so don't do it!   You are getting the buffer of a temporary
CString, so when the object is destroyed at the semicolon the pointer is left pointing to
nonsense.  You made two serious errors here: (a) you tried to do multiple things in a
single line instead of writing multiple lines (see above comment about avoiding writing
complex single lines) and (b) you are using an LPSTR when you should be using a CString!

	CString file = FileDlg.GetFileName();
and that's all!  AVOID doing gratuitous conversions to LPTSTRs unless you need them, and
in this case it makes no sense to want one!
*****
>	LPSTR folderPath = FileDlg.GetPathName().GetBuffer();
****
	CString foldPath = FileDlg.GetPathName();
Same problem as above.  Too much in one line, misuse of temporary object, erroneous
thinking.  And why do you assume that LPSTR makes sense?  It doesn't; the return type is
LPTSTR and saying LPSTR is just flat-out WRONG!  Why do you presume to change the return
type of a function?

B y the way, every GetBuffer must have a ReleaseBuffer, so there are even deeper errors
here!
****
>
>	ULONGLONG fSize = GetFileSizeInByte(fileUrl.GetBuffer());
****
Why GetBuffer? Where's the ReleaseBuffer?  Why not just 
	ULONGLONG fSize = GetFileSizeInByte(fileUrl);
? 

Perhaps you have some fixation about the use of LPSTR.  This is wrong.  The argument to
the function should be either
	const CString &
or
	LPCTSTR
then you don't need to convert the CString to something silly and meaningless like an
LPSTR.  
*****
>
>long GetFileSizeInByte(const char* sFileName)
***
Why do you presume that the character type is 'char'?  LPCTSTR would make sense, but the
above code is no Unicode-aware and should NEVER be written in a modern program.   Note
that if you specify LPCTSTR, then you can pass a CString in as an argument, so there is no
need to use silly GetBuffer calls

A file length is a ULONGLONG.  So why are you declaring the return type as 'long' and why
are you returning negative numbers?  The specification of this function makes no sense!

ULONGLONG GetFileSizeInByte(LPCTSTR fname)
   {
    CFile f;
    if(!f.Open(fname, CFile::modeRead))
       return 0;
    ULONGLONG result = f.GetLength();
    f.Close();
    return result;
   }

****
>{
>  std::ifstream f;
>  f.open(sFileName, std::ios_base::binary | std::ios_base::in);
>  if (f.eof()) { return 0; }
****
USE TWO LINES!
****
>  if (!f.good()) { return -1; }
****
USE TWO LINES!
Returning -1 for a ULONGLONG is meaningless
****
>  if (!f.is_open()) { return -2; }
****
USE TWO LINES
Returning -2 for a ULONGLONG is erroneous
****
>  f.seekg(0, std::ios_base::beg);
>  std::ifstream::pos_type begin_pos = f.tellg();
>  f.seekg(0, std::ios_base::end);
****
A lot of complexity to accomplish what can be done in a single method call when CFile is
being used.  Why use a complex solution when a simple solution exists?
****
>  return static_cast<long>(f.tellg() - begin_pos);
****
And why are you converting a size to a long when the size is a ULONGLONG?  Do you really
mean to throw away the high-order 32 bits of the file size?  
****
>}
>
>fSize is in 80% of cases '-1'. In 15% '-2'. Sometimes it works as
>expected.
****
There are so many errors in the code that until it is rewritten as specified it is
impossible to analyze what is going wrong.  The real problems are a fundamental
misunderstanding about CStrings and data types in general.  Gratuitous and erroneous
conversions, and overly-complex approaches to simple problems only add to the problems.
Rewrite it.
****
>If i set 'folderPath ' to a stistc value and dont call
>FileDlg.DoModal(); all works 100% correct.
****
Of course.  You have far too many errors in the code
****
>
>2. Problem:
>I have some customized Sub-Dialogs (With GUI-Buttons, Custom-Bkg). All
>works correct until i call CFileDialog::DoModal()  /
>GetOpenFileDialog() with return IDOK (means if i choose a File an Click
>Ok, OnCancel the Problem does'nt occur). If i do so and after that call
>my Subdialog, it is completely destroyed. All the GUI Buttons are not
>Visible and not all of them are clickable. The Background is gone and
>just some weird rectangels are visible (a mixture of grey rect's and
>the underlaying bckg).
>If i call a Java FIleOpenDialog via JNI out of this app instead of
>CFileDialog, all works as expected.
****
Until you rewrite the code, any further problems can be attributed to the huge number of
fundamental errors in the current code.  Only after a complete rewrite as specified can
you then worry about other problems.
****
>
>Some Ideas ?
>Does someone know another imlementation of a FileDialog ?
****
The problems are not in CFileDialog.  The problems are where I've indicated.  CFileDialog
is irrelevant to the problem, as far as I can tell.  
****
>
>best regards,
>David
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
11/13/2006 12:24:45 PM
That seems remarkably silly.  Why not just pass folderPath directly?  All you did was a
complicated way of saying
	CString fileUrl = folderPath;
and that accomploishes practically nothing
*****
On 13 Nov 2006 02:54:33 -0800, "dawjdh@googlemail.com" <dawjdh@googlemail.com> wrote:

>Oh, Sorry:
>
>	CString fileUrl;
>	fileUrl.Format("%s",folderPath);
>
>I try'd  several  way's to get the fileSize:
>
>
> /* #### Variante 1 ####*/
>long GetFileSizeInByte(char *fileName){
****
ULONGLONG GetFileizeInByte(LPCTSTR filename)
Two serious errors and you haven't even started to write the code!
****
>
>         long sz = -1;
****
ULONGLONG, not long!
****
>        FILE* f;
>
>        f = fopen (fileName, "rb");
>        if (f)
>        {
>            fseek (f, 0, SEEK_END);
>            sz = ftell (f);
>            fclose (f);
>        }
****
So it appears that if the file is not found, its length is 0xFFFFFFFF, which is something
over 4.2 gigabytes?  Really?  Why does this make sense?
****
>
>	return sz;
>}
> /* #### Variante 2 ####*/
>long GetFileSizeInByte(const char* sFileName){
****
ULONGLONG GetFileSizeInByte(LPCTSTR filename)
Why do you ignore the actual specification of a file length and insist on throwing away
half the value, thus guaranteeing the code is erroneous?
*****
>
>  std::ifstream f;
>  f.open(sFileName, std::ios_base::binary | std::ios_base::in);
>  if (f.eof()) { return 0; }
>  //if (!f.good()) { return -1; }
>  if (!f.is_open()) { return -2; }
>  f.seekg(0, std::ios_base::beg);
>  std::ifstream::pos_type begin_pos = f.tellg();
>  f.seekg(0, std::ios_base::end);
>  return static_cast<long>(f.tellg() - begin_pos);
****
See my previous crtique.  Exceptionally poor coding style, produces an incorrect result,
and does it in a needlessly complex way.
****
>
>}
> /* #### Variante 3 ####*/
>long GetFileSizeInByte( const char * szFileName )
****
ULONGLONG GetFileSizeInByte(LPCTSTR filename)
****
>{
>  struct __stat64 fileStat;
>  int err = _stat64( szFileName, &fileStat );
>  if (0 != err) return 0;
>  return (long)fileStat.st_size;
****
It was correct up to the point where you, for reasons that cannot possibly make sense,
throw away half the bits of the length!
****
>}
> /* #### Variante 4 ####*/
>long GetFileSizeInByte( const char * szFileName )
*****
ULONGLONG GetFileSizeInByte(LPCTSTR filename)
*****
>{
>  struct stat fileStat;
****
Uses the obsolete 32-bit version, so nothing can salvage this code
****
>  int err = stat( szFileName, &fileStat );
>  if (0 != err) return 0;
>  AfxMessageBox(fileStat.st_size);
>  return (long)fileStat.st_size;
>}
>
>Thats all ok, the Problem is the FileOpenDialog, when i do
>GetFileSizeInByte( const char * szFileName ) with a static parameter it
>works in all Variants but not if i first call that Dialog.
****
No, it fails because you have used GetBuffer erroneously.  See my earlier comments.  There
is nothing wrong with CFileDialog, but you made so many errors in handling the strings
that it is amazing that you have ONLY these few problems!
****
>
>> Why not just use the GetFileSize API?
>
>So why would you recommend me to use the GetFileSize API instead of
>other's ?
>
>best Regards,
>David
>
>David Lowndes schrieb:
>
>> >1. Problem:
>> >
>> >	CFileDialog FileDlg(true);
>> >
>> >	INT_PTR nResponse = FileDlg.DoModal();
>> >
>> >	if (nResponse == IDOK){}else{return;}
>> >
>> >	LPSTR file = FileDlg.GetFileName().GetBuffer();
>> >	LPSTR folderPath = FileDlg.GetPathName().GetBuffer();
>> >
>> >	ULONGLONG fSize = GetFileSizeInByte(fileUrl.GetBuffer());
>>
>> What is fileURL ?
>>
>> >long GetFileSizeInByte(const char* sFileName)
>> 
>> Why not just use the GetFileSize API?
>> 
>> Dave
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
11/13/2006 12:39:13 PM
OK, not wishing to be critical, but your coding indicates that you
possibly don't get some key fundamentals of C/C++ programming.

This:
>
	LPSTR file = FileDlg.GetFileName().GetBuffer();
	LPSTR folderPath = FileDlg.GetPathName().GetBuffer();
	CString fileUrl;
	fileUrl.Format("%s",folderPath);

	ULONGLONG fSize = GetFileSizeInByte(fileUrl.GetBuffer());
<

Only needs to be:

	fSize = GetFileSizeInByte( FileDlg.GetPathName() );

Since CString has an automatic conversion to LPCTSTR.

As for your GetFileSizeInByte function, just use the GetFileSize API.

Dave
0
davidl7375 (2060)
11/13/2006 12:39:39 PM
Hi,
thank you for that qualified corrections. I'll try to fix that and to
understand the principles behind that. I will see if that was the
Problem, but what i want to know (you have to confess that the things
you answered have nothing directly to do with what i asked for) , are
there any problems you had before with that CFileOpenDialog alike that
i have ? I just want to be shure and exclude the possibility that
CFileOpenDialog makes some Problems. Is that question ok ? So you push
me in that direction ..... is there any recommendable literature out
there to understand and learn to write that clean code you want me to
write ? It seems to be a real good idea to rewrite that code. I am a
little confused about that hundreds of String types out there. I come
from Java, so there you have only one type for a string. I dont
understand why there are that much possibilities to make the same
thing.

best regards,
David

0
dawjdh (9)
11/13/2006 2:14:05 PM
The reason my answers had little to do with what you asked was that you were asking about
CFileDialog, when all the major failure modes were completely unrelated to CFileDialog and
critically related to the failure to properly use CString values.  Your analysis of the
problem was flawed, based on a misperception of how the code worked.

Whenever you have a problem like this, the FIRST thing to do is to take those awful
multioperator expressions and reduce them to "single assignment" expressions with lots of
intermediate variables; then you can use the debugger to analyze the problem.  You had not
done that, nor had you reported on what the debugger was revealing about the values of the
variables.

I think it is unlikely any of your problems are associated with CFileDialog and there are
so many fatal bugs in how you tried to handle strings that until the string problems are
fixed (and the fatal errors about file length being an 'int') that until those huge number
of bugs are removed, you can't even TALK about problems with CFileDialog.

The basic type you care about is CString.  This is the equivalent to the Java 'String'
type.  There are rare cases in which you need a LPTSTR pointer, but throwing LPSTRs (not
even LPTSTRs) around is just flat-out wrong.  The number of times you would need an LPSTR
is so vanishingly small that when the very rare cases where the need arises, it becomes
obvious.

There are low-level data types of the C language, and they are rarely needed.  But the
C/C++ languages support these.  So they are always there, and there are some rare cases
where you use them, but think of these as exceptions.  The raw data types of C/C++ are

	const char *  - const pointer to 8-bit characters.  Obsolete, avoid
	char * - non-const pointer to 8-bit characters.  Obsolete, avoid
	const wchar_t * - const pointer to Unicode characters.  Obsolete, avoid.
	wchar_t * - non-const pointer to Unicode characters.  Obsolete, avoid.
	"xxx", 'x' - 8-bit string or character constants.  Rarely needed; avoid.
	L"xxx", L'x' - Unicode string or character constants.  Rarely needed; avoid.

Actually, they aren't 'obsolete' in that the LPxSTR typedefs are written in terms of these
underlying types, but the actual *coding* of the primitive data types should be thought of
as an obsolete style.  Windows builds on these types using typedefs and macros:

	LPSTR - pointer to 8-bit characters; rarely needed, avoid except in exceptional
		circumstances where strings are guaranteed to be 8-bit characters.  
	LPCSTR - const verwsion of LPSTR; see LPSTR for qualifications
	LPTSTR - pointer to non-constant ANSI or Unicode string.  Fundamental
		data type, but rarely needed.
	LPCTSTR - pointer to contant ANSI or Unicode string.  Fundamental 
		data type, but very rarely needed 
		Primarily used by API calls that take string arguments, but most
		commonly used in cases where GetBuffer is used to unwrap
		the internal buffer of a CString
	LPWSTR - pointer to non-const Unicode characters.  Rarely needed.
	LPCWSTR - pointer to const Unicode characters.  Rarely needed.
	_T("xxx"), _T('x') - ANSI or Unicode string or character constants.  This should
		be the ONLY way you code a character or string constant, unless
		there are the very rare circumstances where an 8-bit or Unicode constant
		is actually required.

MFC then adds a real 'String' datatype, CString:

	CString - used in almost all cases in programming MFC.  Holds ANSI or Unicode
		string based on compilation mode
	CStringA - CString containing only 8-bit characters.  Usage is about as rare as
		LPSTR, but in most cases is preferred to using a raw LPSTR
	CStringW - CString containing only Unicode characters.  Usage is about as rare
		as LPWSTR, but in most cases is preferred to using a raw LPWSTR
	const CString & - most efficient way to pass a CString as a parameter,
		because no copy of the string is made
	CString & - most common way to pass a reference to a CString
	CString * - very rarely needed; typical example is passing a CString across
		thread boundaries
	GetBuffer - unwraps a buffer of a CString so it can be written to.  Rarely used.
		Using ReleaseBuffer is *mandatory*
	std::string - while part of the Standard C++ Library, has little applicability
		in MFC programming, and has little advantge over CString

Note that any API call or other case where an LPCTSTR is specified, there is an implied
(LPCTSTR) cast operator applied, which returns a pointer to a constant string.

Key to good programming is to use as few operators per statement as possible.  There is
rarely an advantage to this, and it results in code that is hard to read, hard to
understand, hard to debug, and hard to maintain.  Had you not introduced gratuitous usage
of LPSTR and used intermediate variables you would have immediately seen in the debugger
what was going on, and the error caused by the implied destructor of temporary objects
could not have occurred.

Because the debugger is line-oriented, writing more than one statement per line generally
results in code that is difficult-to-impossible to debug.  Program vertically, one
statement per line.  Never use a comma in a declaration list.  One variable, one line.
	CString a, b, c;  // bad style
	CString a;          // one  variable per line.
	CString b;
	CString c;

	if(test) dosomething;  // bad style
	if(test)                           // test is on separate line from then or else
	    dosomething;         
	if(test) {} else {dosomething}  // *exceptionally* bad style
	if(!test)                                       // good style
	     dosomething;
				joe
On 13 Nov 2006 06:14:05 -0800, "dawjdh@googlemail.com" <dawjdh@googlemail.com> wrote:

>Hi,
>thank you for that qualified corrections. I'll try to fix that and to
>understand the principles behind that. I will see if that was the
>Problem, but what i want to know (you have to confess that the things
>you answered have nothing directly to do with what i asked for) , are
>there any problems you had before with that CFileOpenDialog alike that
>i have ? I just want to be shure and exclude the possibility that
>CFileOpenDialog makes some Problems. Is that question ok ? So you push
>me in that direction ..... is there any recommendable literature out
>there to understand and learn to write that clean code you want me to
>write ? It seems to be a real good idea to rewrite that code. I am a
>little confused about that hundreds of String types out there. I come
>from Java, so there you have only one type for a string. I dont
>understand why there are that much possibilities to make the same
>thing.
>
>best regards,
>David
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
11/13/2006 11:50:48 PM
Thank you for your patience, that was realy helpful. I spend the whole
day to convert all the unwell done stuff in my code and was amazed that
most of my Problems that dont have directly to with the changes are
gone (including the on with the CFileDialog).

Joseph M. Newcomer schrieb:

> The reason my answers had little to do with what you asked was that you were asking about
> CFileDialog, when all the major failure modes were completely unrelated to CFileDialog and
> critically related to the failure to properly use CString values.  Your analysis of the
> problem was flawed, based on a misperception of how the code worked.
>
> Whenever you have a problem like this, the FIRST thing to do is to take those awful
> multioperator expressions and reduce them to "single assignment" expressions with lots of
> intermediate variables; then you can use the debugger to analyze the problem.  You had not
> done that, nor had you reported on what the debugger was revealing about the values of the
> variables.
>
> I think it is unlikely any of your problems are associated with CFileDialog and there are
> so many fatal bugs in how you tried to handle strings that until the string problems are
> fixed (and the fatal errors about file length being an 'int') that until those huge number
> of bugs are removed, you can't even TALK about problems with CFileDialog.
>
> The basic type you care about is CString.  This is the equivalent to the Java 'String'
> type.  There are rare cases in which you need a LPTSTR pointer, but throwing LPSTRs (not
> even LPTSTRs) around is just flat-out wrong.  The number of times you would need an LPSTR
> is so vanishingly small that when the very rare cases where the need arises, it becomes
> obvious.
>
> There are low-level data types of the C language, and they are rarely needed.  But the
> C/C++ languages support these.  So they are always there, and there are some rare cases
> where you use them, but think of these as exceptions.  The raw data types of C/C++ are
>
> 	const char *  - const pointer to 8-bit characters.  Obsolete, avoid
> 	char * - non-const pointer to 8-bit characters.  Obsolete, avoid
> 	const wchar_t * - const pointer to Unicode characters.  Obsolete, avoid.
> 	wchar_t * - non-const pointer to Unicode characters.  Obsolete, avoid.
> 	"xxx", 'x' - 8-bit string or character constants.  Rarely needed; avoid.
> 	L"xxx", L'x' - Unicode string or character constants.  Rarely needed; avoid.
>
> Actually, they aren't 'obsolete' in that the LPxSTR typedefs are written in terms of these
> underlying types, but the actual *coding* of the primitive data types should be thought of
> as an obsolete style.  Windows builds on these types using typedefs and macros:
>
> 	LPSTR - pointer to 8-bit characters; rarely needed, avoid except in exceptional
> 		circumstances where strings are guaranteed to be 8-bit characters.
> 	LPCSTR - const verwsion of LPSTR; see LPSTR for qualifications
> 	LPTSTR - pointer to non-constant ANSI or Unicode string.  Fundamental
> 		data type, but rarely needed.
> 	LPCTSTR - pointer to contant ANSI or Unicode string.  Fundamental
> 		data type, but very rarely needed
> 		Primarily used by API calls that take string arguments, but most
> 		commonly used in cases where GetBuffer is used to unwrap
> 		the internal buffer of a CString
> 	LPWSTR - pointer to non-const Unicode characters.  Rarely needed.
> 	LPCWSTR - pointer to const Unicode characters.  Rarely needed.
> 	_T("xxx"), _T('x') - ANSI or Unicode string or character constants.  This should
> 		be the ONLY way you code a character or string constant, unless
> 		there are the very rare circumstances where an 8-bit or Unicode constant
> 		is actually required.
>
> MFC then adds a real 'String' datatype, CString:
>
> 	CString - used in almost all cases in programming MFC.  Holds ANSI or Unicode
> 		string based on compilation mode
> 	CStringA - CString containing only 8-bit characters.  Usage is about as rare as
> 		LPSTR, but in most cases is preferred to using a raw LPSTR
> 	CStringW - CString containing only Unicode characters.  Usage is about as rare
> 		as LPWSTR, but in most cases is preferred to using a raw LPWSTR
> 	const CString & - most efficient way to pass a CString as a parameter,
> 		because no copy of the string is made
> 	CString & - most common way to pass a reference to a CString
> 	CString * - very rarely needed; typical example is passing a CString across
> 		thread boundaries
> 	GetBuffer - unwraps a buffer of a CString so it can be written to.  Rarely used.
> 		Using ReleaseBuffer is *mandatory*
> 	std::string - while part of the Standard C++ Library, has little applicability
> 		in MFC programming, and has little advantge over CString
>
> Note that any API call or other case where an LPCTSTR is specified, there is an implied
> (LPCTSTR) cast operator applied, which returns a pointer to a constant string.
>
> Key to good programming is to use as few operators per statement as possible.  There is
> rarely an advantage to this, and it results in code that is hard to read, hard to
> understand, hard to debug, and hard to maintain.  Had you not introduced gratuitous usage
> of LPSTR and used intermediate variables you would have immediately seen in the debugger
> what was going on, and the error caused by the implied destructor of temporary objects
> could not have occurred.
>
> Because the debugger is line-oriented, writing more than one statement per line generally
> results in code that is difficult-to-impossible to debug.  Program vertically, one
> statement per line.  Never use a comma in a declaration list.  One variable, one line.
> 	CString a, b, c;  // bad style
> 	CString a;          // one  variable per line.
> 	CString b;
> 	CString c;
>
> 	if(test) dosomething;  // bad style
> 	if(test)                           // test is on separate line from then or else
> 	    dosomething;
> 	if(test) {} else {dosomething}  // *exceptionally* bad style
> 	if(!test)                                       // good style
> 	     dosomething;
> 				joe
> On 13 Nov 2006 06:14:05 -0800, "dawjdh@googlemail.com" <dawjdh@googlemail.com> wrote:
>
> >Hi,
> >thank you for that qualified corrections. I'll try to fix that and to
> >understand the principles behind that. I will see if that was the
> >Problem, but what i want to know (you have to confess that the things
> >you answered have nothing directly to do with what i asked for) , are
> >there any problems you had before with that CFileOpenDialog alike that
> >i have ? I just want to be shure and exclude the possibility that
> >CFileOpenDialog makes some Problems. Is that question ok ? So you push
> >me in that direction ..... is there any recommendable literature out
> >there to understand and learn to write that clean code you want me to
> >write ? It seems to be a real good idea to rewrite that code. I am a
> >little confused about that hundreds of String types out there. I come
> >from Java, so there you have only one type for a string. I dont
> >understand why there are that much possibilities to make the same
> >thing.
> >
> >best regards,
> >David
> Joseph M. Newcomer [MVP]
> email: newcomer@flounder.com
> Web: http://www.flounder.com
> MVP Tips: http://www.flounder.com/mvp_tips.htm

0
dawjdh (9)
11/14/2006 2:59:23 PM
Based on the reply I sent you, I've updated my essay on CString data types on my MVP Tips
site.
					joe

On 14 Nov 2006 06:59:23 -0800, "dawjdh@googlemail.com" <dawjdh@googlemail.com> wrote:

>
>Thank you for your patience, that was realy helpful. I spend the whole
>day to convert all the unwell done stuff in my code and was amazed that
>most of my Problems that dont have directly to with the changes are
>gone (including the on with the CFileDialog).
>
>Joseph M. Newcomer schrieb:
>
>> The reason my answers had little to do with what you asked was that you were asking about
>> CFileDialog, when all the major failure modes were completely unrelated to CFileDialog and
>> critically related to the failure to properly use CString values.  Your analysis of the
>> problem was flawed, based on a misperception of how the code worked.
>>
>> Whenever you have a problem like this, the FIRST thing to do is to take those awful
>> multioperator expressions and reduce them to "single assignment" expressions with lots of
>> intermediate variables; then you can use the debugger to analyze the problem.  You had not
>> done that, nor had you reported on what the debugger was revealing about the values of the
>> variables.
>>
>> I think it is unlikely any of your problems are associated with CFileDialog and there are
>> so many fatal bugs in how you tried to handle strings that until the string problems are
>> fixed (and the fatal errors about file length being an 'int') that until those huge number
>> of bugs are removed, you can't even TALK about problems with CFileDialog.
>>
>> The basic type you care about is CString.  This is the equivalent to the Java 'String'
>> type.  There are rare cases in which you need a LPTSTR pointer, but throwing LPSTRs (not
>> even LPTSTRs) around is just flat-out wrong.  The number of times you would need an LPSTR
>> is so vanishingly small that when the very rare cases where the need arises, it becomes
>> obvious.
>>
>> There are low-level data types of the C language, and they are rarely needed.  But the
>> C/C++ languages support these.  So they are always there, and there are some rare cases
>> where you use them, but think of these as exceptions.  The raw data types of C/C++ are
>>
>> 	const char *  - const pointer to 8-bit characters.  Obsolete, avoid
>> 	char * - non-const pointer to 8-bit characters.  Obsolete, avoid
>> 	const wchar_t * - const pointer to Unicode characters.  Obsolete, avoid.
>> 	wchar_t * - non-const pointer to Unicode characters.  Obsolete, avoid.
>> 	"xxx", 'x' - 8-bit string or character constants.  Rarely needed; avoid.
>> 	L"xxx", L'x' - Unicode string or character constants.  Rarely needed; avoid.
>>
>> Actually, they aren't 'obsolete' in that the LPxSTR typedefs are written in terms of these
>> underlying types, but the actual *coding* of the primitive data types should be thought of
>> as an obsolete style.  Windows builds on these types using typedefs and macros:
>>
>> 	LPSTR - pointer to 8-bit characters; rarely needed, avoid except in exceptional
>> 		circumstances where strings are guaranteed to be 8-bit characters.
>> 	LPCSTR - const verwsion of LPSTR; see LPSTR for qualifications
>> 	LPTSTR - pointer to non-constant ANSI or Unicode string.  Fundamental
>> 		data type, but rarely needed.
>> 	LPCTSTR - pointer to contant ANSI or Unicode string.  Fundamental
>> 		data type, but very rarely needed
>> 		Primarily used by API calls that take string arguments, but most
>> 		commonly used in cases where GetBuffer is used to unwrap
>> 		the internal buffer of a CString
>> 	LPWSTR - pointer to non-const Unicode characters.  Rarely needed.
>> 	LPCWSTR - pointer to const Unicode characters.  Rarely needed.
>> 	_T("xxx"), _T('x') - ANSI or Unicode string or character constants.  This should
>> 		be the ONLY way you code a character or string constant, unless
>> 		there are the very rare circumstances where an 8-bit or Unicode constant
>> 		is actually required.
>>
>> MFC then adds a real 'String' datatype, CString:
>>
>> 	CString - used in almost all cases in programming MFC.  Holds ANSI or Unicode
>> 		string based on compilation mode
>> 	CStringA - CString containing only 8-bit characters.  Usage is about as rare as
>> 		LPSTR, but in most cases is preferred to using a raw LPSTR
>> 	CStringW - CString containing only Unicode characters.  Usage is about as rare
>> 		as LPWSTR, but in most cases is preferred to using a raw LPWSTR
>> 	const CString & - most efficient way to pass a CString as a parameter,
>> 		because no copy of the string is made
>> 	CString & - most common way to pass a reference to a CString
>> 	CString * - very rarely needed; typical example is passing a CString across
>> 		thread boundaries
>> 	GetBuffer - unwraps a buffer of a CString so it can be written to.  Rarely used.
>> 		Using ReleaseBuffer is *mandatory*
>> 	std::string - while part of the Standard C++ Library, has little applicability
>> 		in MFC programming, and has little advantge over CString
>>
>> Note that any API call or other case where an LPCTSTR is specified, there is an implied
>> (LPCTSTR) cast operator applied, which returns a pointer to a constant string.
>>
>> Key to good programming is to use as few operators per statement as possible.  There is
>> rarely an advantage to this, and it results in code that is hard to read, hard to
>> understand, hard to debug, and hard to maintain.  Had you not introduced gratuitous usage
>> of LPSTR and used intermediate variables you would have immediately seen in the debugger
>> what was going on, and the error caused by the implied destructor of temporary objects
>> could not have occurred.
>>
>> Because the debugger is line-oriented, writing more than one statement per line generally
>> results in code that is difficult-to-impossible to debug.  Program vertically, one
>> statement per line.  Never use a comma in a declaration list.  One variable, one line.
>> 	CString a, b, c;  // bad style
>> 	CString a;          // one  variable per line.
>> 	CString b;
>> 	CString c;
>>
>> 	if(test) dosomething;  // bad style
>> 	if(test)                           // test is on separate line from then or else
>> 	    dosomething;
>> 	if(test) {} else {dosomething}  // *exceptionally* bad style
>> 	if(!test)                                       // good style
>> 	     dosomething;
>> 				joe
>> On 13 Nov 2006 06:14:05 -0800, "dawjdh@googlemail.com" <dawjdh@googlemail.com> wrote:
>>
>> >Hi,
>> >thank you for that qualified corrections. I'll try to fix that and to
>> >understand the principles behind that. I will see if that was the
>> >Problem, but what i want to know (you have to confess that the things
>> >you answered have nothing directly to do with what i asked for) , are
>> >there any problems you had before with that CFileOpenDialog alike that
>> >i have ? I just want to be shure and exclude the possibility that
>> >CFileOpenDialog makes some Problems. Is that question ok ? So you push
>> >me in that direction ..... is there any recommendable literature out
>> >there to understand and learn to write that clean code you want me to
>> >write ? It seems to be a real good idea to rewrite that code. I am a
>> >little confused about that hundreds of String types out there. I come
>> >from Java, so there you have only one type for a string. I dont
>> >understand why there are that much possibilities to make the same
>> >thing.
>> >
>> >best regards,
>> >David
>> Joseph M. Newcomer [MVP]
>> email: newcomer@flounder.com
>> Web: http://www.flounder.com
>> MVP Tips: http://www.flounder.com/mvp_tips.htm
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15975)
11/16/2006 4:19:55 AM
Reply:

Similar Artilces:

Problem with komma versus period in Excel
Hej I am have problems with the use of period in Excel. I Denmark komma is the decimal seperator. If I convert (from within VB Editor) the content of a cell from "6340,00" to text and replace the komma with period I get "6340" (I wanted "6340.00). If I make the convertion in Excel and record the macro at the same time I get the desired result i my sheet. BUT when I put in my code in VBA and run it from here I still get the wrong result, "6340" and not "6340.00". I know Excel (VBA) transform "." to "," probably acording to...

Report Writer Text Spacing Problems While Modifying a PO form
Due to Report Writer static text field size limitations, I am forced to try to use two adjacent text fields to complete a sentence. I am having an inordinate amout of problems trying to get words to align in sentences with the correct amount of character spacing between words that span the text field boundaries. And, the process of toggling between Report Writer and Dyamics to get the Purchase Order form to reprint is time consuming. What am I missing (besides patience)? -- Jay Jay, 1) Setup a calculated field for your static text. Set the result type to String, and use the Constant...

Help! Setfocus problem
i ave a dropdown field on the first tab. I use setfocus so that it selects a different field to stop users scrolling down and changing the selection on the load event. Problem When a user changes tab and come back to the origional tab the setfocus doesnt run as the form is already loaded. How do you get around this? This is driving me and users mad at minute...please help before i open another bottle of dark rum! Hi Brian, Check out following URL; how to fire onclick event on tab click. It may help you. http://crmrocks.net/?p=16 -- PLEASE do click on Yes or No button if this post wa...

Exchange Patch (KB912442) causes problem w/ share login accts
Exchange2003 std SP2 w/ Office 2003 & XP clients. We have several users who shares a computer, so instead of logging in w/ different users accts, I set them up w/ a shared logging and access Outlook w/ multiple Mail profiles. However, after installing KB912442, it blocks these users from sending emails. It gives them an message that the shared login doesn't have the right to send emails on behalf of this user. I checked the mailbox rights in AD Users and Computers, the shared login has Read & Full mailbox rights permissions. Any idea how to fix this. Thanks in advance. ...

Hard drive crash
I had a hard drive crash. I have recovered the files bt can not open Money from them. Any ideas? In microsoft.public.money, Elamt wrote: >I had a hard drive crash. I have recovered the files bt can not open Money >from them. Any ideas? You will need to install Microsoft Money. What you do may be affected by the version, but in no case will an older version open a file from a newer version. Save the *.mny and *.mbf files from the crashed hard drive. Make an extra copy in case your new media fails. ...

Safe Pay Check Amount Problem
I am trying to setup Safe Pay. Everything seems to be working fine except for one annoying quirk. Our bank's Positive Pay data format gives us 12 characters for check amounts ($$$$$$$$$$¢¢). The file that Safe Pay generates is working perfectly except for those checks that are greater than $9,999,999.99 (9 characters). If the check amount is greater than that (say $10,000,000.00), the value that the Safe Pay file shows for that check is 002147483647. And, even if none of the individual checks exceed $9,999,999.99, if the total of the checks in the batch exceeds that a...

Internet connection problem
Hi. I hope someone is able to cast some light on a problem. We have a home network (all computers running XP) some wired and some wireless. For about a month now we have intermittent connection problems in that any one computer (randomly) will not connect to internet. I think all of the computers have suffered from the problem. Rebooting the affected computer makes no difference but rebooting the router can sort it until the next time. Even my mobile phone occasionally cannot connect. In Firefox the message is just "server not found". Pinging an IP address results in a time...

Problem with charting Net income vs Year
Im having some problems with my Excel chart. It will not plot Net Income vs Year. It keeps trying to treat Year as a different data series. It will work if I use text i.e. a1990, a1991, etc. but it refuses to use 1990, 1991... Any Ideas??? Use an "XY (Scatter)" chart, instead of a "Line" chart. Jerry Hunter wrote: > Im having some problems with my Excel chart. It will not plot Net Income vs Year. It keeps trying to treat Year as a different data series. It will work if I use text i.e. a1990, a1991, etc. but it refuses to use 1990, 1991... Any Ideas??? Delete the co...

SK 40175 Tuff-1 1/2-Inch Drive 15-Inch Reversible Ratchet
Price:$90.24 Image: http://thediscounfinder.info/image.php?id=B0009U5RRM Best deal: http://thediscounfinder.info/index.php?id=B0009U5RRM Item #: SKT40175. Features & Benefits:Tuff 1(r) Ratchets 72 tooth head design delivers a short 5" stroke for use in tight areas.17 teeth engage when torque is applied to provide a strong grip without slippage.Thumb falls naturally into position, giving instant control with one hand.Easy to reverse, 4 point cap.SuperKrome plating for long tool life and maximum corrosion resistance.Description: 15" Reversible Tuff Customers also search for:...

Excel hyperlink problem
Hello everyone, I have a strange excel problem and it's driving me nuts - I would be seriously grateful if someone could help me out! A colleague has this excel document with a huge number of hyperlinks in it, well over 1000 (don't ask me why she wants to use excel - she just does). The hyperlinks are in this format and are using DFS: \\cc\root\pte\tru\ch\scandata\Archaeology\1980\xxx.pdf Whenever she clicks on a link, a pdf from another area of the network is opened. Quite simple and no problems so far. However, as of yesterday, whenver she makes any kind of change to the excel fi...

securety problem
Hi, I start an app in vb with this code: ActiveWorkbook.FollowHyperlink "C:\te.exe" I always get a warning about hyperlinks that can be harmfull to computer. How can I bypas this warning. I �ve put my macro securety on low and trust all installed add-ins and templates + trust acces to visiual basic project. Is there a way so the warning won�t show Thanks Johan -- climax ------------------------------------------------------------------------ climax's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=30816 View this thread: http://www.excelforum.com/...

WdfUsbTargetDeviceCreate creates NULL Control Pipe Handle
Hi, We have a usb composite device which has one mass storage interface and another as a network interface. We are developing a WDF driver (NDIS-USB) for the network interface. Immediately after WdfUsbTargetDeviceCreate if I break into the debugger and examine the newly created device, then I see that the Control Pipe Handle is NULL! Here is the actual output: -------- kd> !WDFUSBDEVICE 0x0000057f`fe5905f8 WDFUSBDEVICE 0000057ffe5905f8 ============================= Config descriptor fffffa80037216b0, device descriptor fffffa8001a6fb58 Control USBD_PIPE_HANDLE 000000000000...

Problems opening/saving attachments
I am unable to open or save any .rtf file attachments - this started happening today, previously there were no problems with .rtf files. When I try to open such an attachment I get this message: Can't create file: xyz.rtf Right click the folder you want to create the file in, and then click Properties on the shortcut menu to check your permissions for the folder. What folder is this? I am trying to open the attachment not creat the file! Also, when I try to send an rtf file as an attachment, in the email message the file does not show in the attachments section but the receipient actu...

Prevent users from saving music and pictures to their hard drives without folder redirection?
Hi there. I'm wondering if there is a way via GPO or anything else to prevent users from saving music and pictures to their local hard drives without using any type of profile or folder redirection. Thanks. ...

wire transfer download problems
I made an international wire transfer of $5000 from my US bank. The receiving bank in Panama took $15 as a service fee and credited my account with $4885. Somehow my US bank now wants to show the amount as $4885 during downloads to my checking account. But some genie reminds Money 2004 that the original amount was $5000 which triggers a discrepancy. As a result, this transaction wants to download each and every time, whether I change, accept, or whatever. Thanks for help. In microsoft.public.money, lanecito wrote: >I made an international wire transfer of $5000 from my US bank. Th...

Interesting TIF file problem
At the company I work for, we have someone that exports AutoCAD drawings to a TIF file, then inserts the TIF file into an Excel spreadsheet. We have quite a few of these. Other users can open this spreadsheet, view it, do a print preview, but when they try to print the file the inserted picture does not show up. All that prints is a box with the broken url red x document image. It seems that the problem is with Office XP. The Excel files are created with Office 2000, and they print fine from Excel 2000. On Office XP and Office 2003, the file won't print properly (all systems are ru...

Annoying problem with lookup field
On a client, I have a MOSS 2007 portal with two lists which are not wroking as expected. One contains people and the other one contains a lookup field based on data from the first list. When someone which hasn't got administrative rights logs in and tries to see the properties of any element in the second list (on DispForm.aspx), they can't see the lookup field value, and if they try to edit the element, the dropdown control used to choose a person from the first list appears empty. Administrator don't have this problem. The users having the problem have collaboration rig...

Can I show server name instead of drive letter?
When using the =Cell("filename") function, I would like to show the actual server instead of a drive letter because the letter is dependent on where the server is mapped and not all users have the same mapping. Is this possible? Try using: \\ServerName\drive\... where ServerName is the name of the server and drive is the appropriate drive, and then find the file on the drive from that point. "bfant" wrote: > When using the =Cell("filename") function, I would like to show the actual > server instead of a drive letter because the letter is dependent on...

Problem with vba code to export query result in excel
Hi, I have a access report that exports to excel with click of a button after choosing parameters. This works well. However I have to modify couple of fields to utilize formula in the export module. I am not sure how to do this. I am writing the above code which seems to cause problem. I appreciate any help to resolve this issue. Thanks. Code: If lngColumn = 12 Then xlc.Offset(0, lngColumn).Value = =([UnitPrice]*[OriginalShippedQty])/1000 End If It seems the fields UnitPrice and OrigianalShippedQty are not being recognized here Jack wrote: >Hi, >I have a acces...

re install Pub 2000 problem.
Hello and I hope I'm In the right newsgroup. My problem is I've had to re install my Office 2000 Disc2 and now when I want to start publisher the message box tells me I am trying to access a program that needs the cd. When I installed it, I checked for Publiher to "run all from my computer" I've un installed and re installed, still need disc. what am I doing wrong? Thanks for your help, John :) Johnny1r wrote: > Hello and I hope I'm In the right newsgroup. My problem is I've had to > re install my Office 2000 Disc2 and now when I want to start publis...

Uploading problems
Hi all, I hope someone can help me with a few difficulties i'm having uploading my website. 1. When I upload, only the first page is uploading - so pages 2-7 don't appear 2. Images do not download with the webpages so when you type in the url, you simply see a blank space where a photo should be with a small icon at the top left courner which sometimes offers the option of 'show picture'. 3. The webpage is positioned to the left of the window when it appears and doesn't centre itself to the page so there is a huge chunk of white space to the right of the window. Can ...

"Archive all messages sent or received by mailboxes on this store" option problem
I want to backup the all message sent or received by mailboxes, I find that there is an option "Archive all messages sent or received by mailboxes on this store " in Exchanger 2003. I had selected this option and forward to public folder. But I found that not all message will be archived. - All message sent by mailboxes can be archived - Some Messages come from mailboxes will not be archived Eg: yahoo, hotmail, and other company Is this option not archive this message ? Any other setting need to configure ? Dennis ...

CHtmlView shutdown problem
Hi! We created an MFC regular DLL whch is loaded by an old MFC-app (built with VC++ 6.0) but we dont have access to the source of this app, just an DLL-interface. our regular DLL loads several MFC extension DLLs. one of the extension DLLs uses a CHtmlView based object which is used within a docking pane, we dont use document/view-architecture. when I shutdown the app, it takes more than 1 minute till the CHtmlView object gets detstroyed. this effect doesnt occur when we load our DLLs from within an new MFC app, built with VC++.NET, everything shuts down fine. due to the fact that there is n...

Inventory Adjustments with problems
Hi In this moment I have some journal entry in financial module with transactions that i never saw before. The bachumb is something like 'GLTRX024134', they are not sequencial. In the descriptn, this has a link to a transaction from inventory adjustment, but with a change... if for example the transaction from inventory is AJ00000007, in this reference is IVAAJ00000007, this is happening with the transfers too. Any idea is welcome!!! Thanks in advance ...

Attachment File Problem
hi my problem is , when i attachment any file to the new mail i can't attachment the file whyyyyyyyyyy i mean when we attachment any file to the mail must be automatic open new filed where it show us the attachnebt file ?????? but it's not happend in my system second problem when i recive any mail whit attachment file it gave me the message "OE REMOVED ACCESS TO THE FOLLOWING UNSAFE ATTACHMENTSIN YOUR MAIL" HELP Pls. thank's You'll need to be a lot more specific if you expect anyone to know what you're talking about - exact error message is? Post it in t...