Click here to Skip to main content
15,886,017 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
I wrote the code to write binary data in my file as follows:-
C++
while(1)
	{

 		iResult = send( ThreadSocket, data, (int)strlen(data), 0 );
		if (iResult == SOCKET_ERROR)
		{
			printf("send failed with error: %d\n", WSAGetLastError());
			closesocket(ConnectSocket);
			WSACleanup();
			return 1;
		}

		printf("Bytes Sent: %ld\n", iResult);
		int prev=0;
		int w =0;
		do {


			iResult1 = recv(ThreadSocket, recvbuf, recvbuflen, 0);
			if ( iResult1 > 0 )
			{	
				wLog->WriteErrorLog(recvbuf);
				for(j=0;j<=iResult1;j++)
				{
					common[w] = recvbuf[j];
					w++;

				}
				//count++;

				printf("Bytes received: %d\n", iResult1);
				memset(recvbuf, 0, sizeof(recvbuf));
				//printf("value of count is %d\n",count);
			}
			else if ( iResult1 == 0 )
				printf("Connection closed\n");
			else
				printf("recv failed with error: %d\n", WSAGetLastError());

		} while( iResult1 > 0 );
	

		wLog->WriteInfoLog(common);
	

		WriteToDataFile1(common);
		parse(common);
	
		wLog->CreateLogFolder1();
	wLog->CreateLogFile1();
			wLog->WriteBinary(common);
				memset(common, 0, sizeof(common));
		Sleep(10000);
		//Sleep(5000);
	}



C++
#include "Log.h"


extern  char *a;



Log::Log()
{
	//iLogLevel = 0;
}
Log::~Log()
{

}
void Log ::CreateLogFolder1()
{
	//WriteToLog4("Log :Entering Create folder");
	//get the path of ini file
	//	TO DO
	//check status of ini file
	//	TO DO
	//read ini file and get log directory path
	//	TO DO
	//create log folder
	_mkdir( szLogDir1);
	//WriteToLog4("Log :Leaving Create folder");
}
void Log ::CreateLogFile1()
{
	char    szDate[12];
	char buf[150];
	int i=0;
	int iLevel;

	//get the path of ini file
	//	TO DO
	//check status of ini file
	//	TO DO
	//read ini file and get log directory path
	//	TO DO
	//create log file
	_strdate( szDate );
	//logfilename format ServerManagermm-dd--yy
	strcpy(buf,szLogDir1);
	strcat(buf, "\\");
	strcat(buf, "\\");
	strcat(buf,a);
		
	strcat(buf,szDate);
	strcat(buf,".txt");

	while(buf[i] != '\0')	// mm/dd/yy to mm-dd-yy conversion
	{
		if(buf[i] == '/')
			buf[i] = '-';
		i++;
	}

	ofstream pOS(buf,ios::app);
	pOS<<"\nBinary Strarted..\n"<<endl;
	pOS.close();

}
void Log ::WriteBinary(char *str)
{
	char    szDate[12];
		char    szTime[12];
		char buf[2000];
		int i=0;
		_strdate( szDate );
		_strtime( szTime );

		strcpy(buf,szLogDir1);
		strcat(buf, "\\");
		strcat(buf,a);
		strcat(buf,szDate);
		strcat(buf,".txt");
		while(buf[i] != '\0')
		{
			if(buf[i] == '/')
				buf[i] = '-';
			i++;
		}
		ofstream pOS(buf,ios::app);

		sprintf(buf,"%s::%s :Data is :%s", szDate, szTime, str);
		pOS<<buf<< endl;
		pOS.close();


}


The output of the "wLog->WriteBinary(common);" statement when i see is as follows:-
Binary Strarted..

10/01/12::19:17:42 :Data is :RE00002211050046

Binary Strarted..

10/01/12::19:17:58 :Data is :RE0000221105004

Binary Strarted..

10/01/12::19:18:31 :Data is :RE000022110500460 0.00 0.1 0.126.9#####  122    0#####    0#####- 1221.004.00 0: 03.000.00 4: 019:17 0: 023:17############2.00.0   23:47ƒ
Binary Strarted..

10/01/12::19:19:01 :Data is :RE000022110500460 0.00 0.1 0.126.9#####   18    0#####    0#####-  181.004.00 0: 00.000.00 4: 019:17 0: 023:17############2.00.0   23:47ž
Binary Strarted..

10/01/12::19:19:17 :Data is :RE00002211050046

Binary Strarted..

10/01/12::19:19:33 :Data is :RE00002211050046

I always get the 138byte data from the machine sometimes whole 138byte are written and sometimes on some are written as shown above can anyone tell whats the problem and how to remove?
Posted

The issue is that you are not writing binary data, you are writing character strings. You need to use the fwrite()[^] function to write the data, so you are sure that you write any bytes following a null byte.
 
Share this answer
 
Comments
Tarun Batra 1-Oct-12 11:07am    
Sir you are correct we should fwrite but as shown in my above problem(under Binary started text) sometimes the whole buffer is written and sometimes not why is it so?
Richard MacCutchan 1-Oct-12 11:13am    
Because you are using sprintf() with a %s format specifier which tells the output handler that the parameter is a null terminated string, so it stops writing as soon as it sees a null character. You cannot write binary data using sprintf() in this way.
Tarun Batra 1-Oct-12 11:20am    
Can u tell what to use instead of sprintf?
Richard MacCutchan 1-Oct-12 11:23am    
Well I could, but I think saying it twice should be enough.
Tarun Batra 1-Oct-12 11:20am    
As i have to write binary data that i receive in the following format DATE:TIME:DATA even if the DATA contains null character it should print all the data
You seem to be struggling with some of the basic concepts here and getting a bit confused about what needs to be done. There is no need to keep copying data from one place to another just so you can write it out. Try something like:
C++
char    szDateTime[12];
int recordLength = 138; // this should contain the real length of the data
_strdate( szDateTime);
// write the date followed by '::'
fwrite(szDateTime, 1, strlen(szDateTime), log);
printf("Date: %s", szDateTime);
fwrite("::", 1, 2, log);
_strtime( szTime );
// write the time
fwrite(szDateTime, 1, strlen(szDateTime), log);
printf("Time: %s", szDateTime);
// write the data separator
fwrite(":Info:", 1, 2, log);
// optionally write a word containing the data length
fwrite(recordLength, sizeof(int), 1, log);
// write the data buffer
fwrite(str, 1, recordLength, log);
printf("Data: %s", str);


Note that as long as the data contains null bytes, it will not be possible to print it all to the screen. Some lines will appear truncated and some may overlap the following lines; this is a consequence of handling binary data and there is nothing you can do to avoid it.
 
Share this answer
 
Comments
Espen Harlinn 1-Oct-12 15:54pm    
2x5 :-D
Richard MacCutchan 2-Oct-12 3:17am    
Thanks.
If you use a limited length format string for a number (e. g. "%4d") , and the number is too big to fit, it will be represented as a sequence of '#' instead.

Suggested fix: check your formats and make sure the numbers do fit in, or write the number in an unrestricted length format into an intermediate string and then copy what you want to see from there.
 
Share this answer
 
Comments
Tarun Batra 1-Oct-12 10:50am    
Sir the problem that i can understand is "sprintf(buf,"%s::%s :Data is :%s", szDate, szTime, str);" sprintf breks at null character but if i get the null character in response how can i print it into buffer?
Stefan_Lang 1-Oct-12 11:16am    
Ah, ok. Didn't get that the truncation was your problem. I believe Richard has it right.
Richard MacCutchan 1-Oct-12 10:55am    
That's not true, the number still gets printed correctly, as described here.
Stefan_Lang 1-Oct-12 11:00am    
Hm, I might have misremembered this, but I'm sure I've seen '###' style output before, and thought it was due to unsufficient width. Anyway, thanks for the link.
Richard MacCutchan 1-Oct-12 11:10am    
You are probably thinking of Excel.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900