Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert char[] to CString (NULL problem)

Status
Not open for further replies.

zoomby

Programmer
Aug 5, 2002
60
DE
Hi!

I'm using the CFile.Read() for reading a file, and have to set a char[] buffer. When I copy the char[] into a CString a can see the NULL-Terminator of the char[] as garbage chars( something like "ÌÌÌÌÌÌ"...).
I got rid of it by using a loop and ommitted the last
char[] element.
Is there a better way to get rid of the NULL at the end of a char[]?

bye
Chris
 
Hi,
suppose your program ...


char szMyBuf[100] ;

// at this point your buffer has garbage inside

CFile f ;
UINT nr;
....
nr=f.Read( szMyBuf, 3 ) ;
if( nr!=3 )
//read error

Your buffer contains 3 bytes read from file and it has
not NULL chars: from position 3 to 99, yous buffer is
unchanged. What you see by debug (IIII), is not NULL
terminator, but the same garbage that was before.

The read function does not add a null at the end of the string: you have to do.

szMyBuf[nr]=0; // or '\0' (is always 0 )

and now you can

cMyString = szMyBuf ;


bye.

P.S. : C language is not as VB or Windows OS:
it is very the flexible, but you have to
make by yorself many things!
 
hi!
thanks for your answer. But there is still a strange char at the end of the char[] buffer.
Here is the code. the value of buff[l] is "ý". So CString text will still contain garbage chars.

CFile f;
if (f.Open("text.txt",CFile::modeRead))
{
long l = f.GetLength();
char* buff=new char[l];
f.Read( buff, l);

CString text;
text=buff[l];

}
 
hi,

some observ.s:

1) I don't know the content of file, but if it
is a text file, it may contains also CR and LF.

2) Some files coming from DOS contains at the end a Ctrl-z
and some funcions dont read it, other yes, and also this
can go inside your read.

3) Read function is thinked to read any type of file,
also binary file, ( you can read file whit 2 longword
inside it without CRLF ); this function does not
thinks to put NULL in your buffer.

4) to read N chars from a file, you have to allocate
N+1 chars in buffer and set

buff[N]=0 ; // you have to do !

5) Why CSting text=buffer[l] and not text=buffer ?


b y e

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top