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 Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Writing to file

Status
Not open for further replies.

makaveliuk

Programmer
Dec 1, 2003
46
GB
I am running a file copy routine i.e. CreateFile(), then a ReadFile() -> WriteFile() loop, but I want to write a few strings to the top of the file before the loop, how do I write the contents of a CString to the file with WriteFile()?
 
CString str="abdc";
DWORD dw = 0;
OVERLAPPED os ;
// hFile obtained from CreateFile() and was not with FILE_FLAG_OVERLAPPED flag
BOOL bDone = WriteFile( hFile, (LPCVOID)str, str.GetLength(), &dw,NULL);
or
// hFile obtained from CreateFile() and with FILE_FLAG_OVERLAPPED flag
BOOL bDone = WriteFile( hFile, (LPCVOID)str, str.GetLength(), &dw,&os);
-obislavu-
 
I tried that but I only get half the string in the file with null characters after each character.

What am I doing wrong?
 
try using

str.c_str()

instead of just "str"

Skute

"There are 10 types of people in this World, those that understand binary, and those that don't!"
 
It says 'c_str' is not a member of CString when I try that.
 
sorry i was thinking of the STL string class.

Try:

str.GetBuffer(int Length)

That will give you a pointer to the actual buffer

Skute

"There are 10 types of people in this World, those that understand binary, and those that don't!"
 
The following will create the C:\\text.txt file and if open it in notepad you will see :
abcd
George

Code:
CString str="abdc\r\n";
	CString str2="George\r\n";
	DWORD dw = 0;
	OVERLAPPED  os ;
	HANDLE hFile = CreateFile("C:\\test.txt",
   	GENERIC_WRITE,      
  	FILE_SHARE_WRITE,        
	NULL,
 	CREATE_NEW,  
  	FILE_ATTRIBUTE_NORMAL, 
  	NULL  );
	//hFile obtained from CreateFile() and was not with FILE_FLAG_OVERLAPPED flag
	BOOL bDone = WriteFile( hFile, (LPCVOID)str, str.GetLength(), &dw,NULL); 
	WriteFile( hFile, (LPCVOID)str2, str2.GetLength(), &dw,NULL); 
	//or
	// hFile obtained from CreateFile() and with FILE_FLAG_OVERLAPPED flag
	//BOOL bDone = WriteFile( hFile, (LPCVOID)str, str.GetLength(), &dw,&os); 
	CloseHandle(hFile);

-obislavu-
 
Thanks for the code but it does the same thing, it looks okay when I open it in Wordpad but has null characters after each character when I open it in Wordpad or Hexedit.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top