Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
I wrote the code to write binary data in my file as follows:-
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);
	}
 

#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 1-Oct-12 4:10am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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:
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.
  Permalink  
Comments
Espen Harlinn at 1-Oct-12 15:54pm
   
2x5 :-D
Richard MacCutchan at 2-Oct-12 3:17am
   
Thanks.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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.
  Permalink  
Comments
Tarun Batra at 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 at 1-Oct-12 11:13am
   
Because you are using <code>sprintf()</code> with a <code>%s</code> 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 <code>sprintf()</code> in this way.
Tarun Batra at 1-Oct-12 11:20am
   
Can u tell what to use instead of sprintf?
Richard MacCutchan at 1-Oct-12 11:23am
   
Well I could, but I think saying it twice should be enough.
Tarun Batra at 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
Tarun Batra at 2-Oct-12 1:09am
   
Sir just a Bit more help of your is required i modified my WriteBinary function as shown in above code as void Log ::WriteBinary(char bufg[139]) { char szDate[12]; char szTime[12]; char buf[2000]; char bufpath[2000]; int i=0; _strdate( szDate ); _strtime( szTime ); strcpy(buf,szLogDir1); strcat(buf, "\\"); strcat(buf, "\\"); strcat(buf,a); strcat(buf,szDate); strcat(buf,".txt"); memcpy(bufpath,buf,sizeof(buf)); while(buf[i] != '\0') { if(buf[i] == '/') buf[i] = '-'; i++; } ofstream pOS(buf,ios::app); fprintf((FILE*)bufpath, "%s::%s::DATA IS::", szDate, szTime);//Now my code break here fwrite(bufg, 1, 138, (FILE*)bufpath); fprintf((FILE*)bufpath, "\n"); /*sprintf(buf,"%s::%s :Data is :%s", szDate, szTime, bufg); pOS&lt;&lt;buf&lt;&lt; endl;*/ pOS.close(); }
Richard MacCutchan at 2-Oct-12 3:20am
   
This is still not going to work. Go and study my Solution 3 above to see how you should be doing it.
Tarun Batra at 1-Oct-12 11:14am
   
Is there any other way,Please tell
Tarun Batra at 1-Oct-12 11:16am
   
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
Richard MacCutchan at 1-Oct-12 11:22am
   
What is your difficulty? I explained to you that you need to use the <code>fwrite()</code> function to write all the data into your file. If you don't want to do this then your program is not going to work.
Tarun Batra at 1-Oct-12 11:33am
   
Now can you tell me now what to do under the circumstances i wrote below?
Tarun Batra at 1-Oct-12 11:28am
   
int WriteToDataFile1(char* str) { FILE* log; char szDate[12]; char szTime[12]; char buf_buff[2500]; memset(buf_buf, 0, sizeof(buf_buff)); _strdate( szDate ); _strtime( szTime ); sprintf(buf_buf,"%s::%s:Info:%s", szDate, szTime, str);log = fopen(BufferFilePath11, "wb"); if (log == NULL) return -1; sprintf(buf_buf,"%s::%s:Info:%s", szDate, szTime, str); fwrite(buf_buf,1,sizeof(buf_buf),log); fclose(log); return 0; }Acc to you i use thr fwrite function but as i told you i have to write the data as "DATE:Time:DATA" so i used "sprintf(buf_buf,"%s::%s:Info:%s", szDate, szTime, str);" won't i will get stuck here?
Richard MacCutchan at 1-Oct-12 12:01pm
   
I am sorry to belabour this point but <b>you cannot use <code>sprintf()</code></b> to write binary data, you will not get the results you want. Nor must you use <code>sizeof()</code> to set the number of characters to write, since that may not be the same as the number in the buffer. What you should do is: 1. Write the date and time using normal formatting. 2. Write the binary data direct from its receive buffer using the length that you get from your reader routine. 3. You may also need to write some marker in front of each record to tell you how long the record is.
Tarun Batra at 1-Oct-12 12:16pm
   
Can u please give some psudo code...It will be a much help from your side
Tarun Batra at 1-Oct-12 13:21pm
   
sir you were correct that fwrite will work but i got into two problems now one is how to write date and time before the actual data to write and every time WriteToDataFile1() function the data is written in the same line rather than one after another by this i mean that data is written like this DATA DATA BUT IT SHOULD BE DATA DATA
Richard MacCutchan at 1-Oct-12 13:34pm
   
You just have to simulate what you were doing with <code>sprintf()</code>: 1. Write a record header, an integer value giving the record length. You can calculate this from the length of the string data plus the length of the binary data. 2. Write the string data to the file. 3. Write the binary data. If you want some different format then change it according to your requirements. It is always a good idea to sketch it out on paper first to see what items you want in each position of your record. If your binary data is always a fixed length then you do not need the control word at the beginning.
Tarun Batra at 1-Oct-12 13:38pm
   
Sir can you please give the pseudo code i will get 138 byte from the server that is the binary data it is fixed it will be of 138 byte
Richard MacCutchan at 1-Oct-12 13:45pm
   
What pseudo code? Surely, you can figure out how to add a few numbers together?
Tarun Batra at 1-Oct-12 14:04pm
   
sir for sample i did like this char buf[100]="RE00002270150\0 0210 0"; char szDate[12]; char szTime[12]; char buf_buff[2500]; memset(buf_buf, 0, sizeof(buf_buff)); _strdate( szDate ); _strtime( szTime ); sprintf(buf_buf,"%s::%s", szDate, szTime); printf("common buf is %s\n",buf_buf); int w=strlen(buf_buf); int k=20; for(int i=0;i&lt;=28;i++) { buf_buf[k]=buf[i]; k++; } buf_buf[k]='\0'; WriteToDataFile1(buf_buf); Can you please tell me how to write the data in next line 2nd time the WriteToDataFile1() function is called
Tarun Batra at 1-Oct-12 14:25pm
   
Sir You are superb just tell me one more thing how to write the data one after another the whole data is written in one line even after subsequent function call i added \n also after the data also
Tarun Batra at 1-Oct-12 14:39pm
   
i added '\n' also put not getting data in the next line
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
Comments
Tarun Batra at 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 at 1-Oct-12 11:16am
   
Ah, ok. Didn't get that the truncation was your problem. I believe Richard has it right.
Richard MacCutchan at 1-Oct-12 10:55am
   
That's not true, the number still gets printed correctly, as described <a href="http://msdn.microsoft.com/en-us/library/25366k66.aspx">here</a>.
Stefan_Lang at 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 at 1-Oct-12 11:10am
   
You are probably thinking of Excel.
Stefan_Lang at 1-Oct-12 11:17am
   
Now that you mention it... :o)

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

  Print Answers RSS
0 Dnyaneshwar@Pune 1,300
1 Sergey Alexandrovich Kryukov 667
2 Tadit Dash 350
3 ravikhoda 300
4 Manas Bhardwaj 240
0 Sergey Alexandrovich Kryukov 11,224
1 OriginalGriff 6,897
2 Peter Leow 4,795
3 Abhinav S 3,838
4 Maciej Los 3,575


Advertise | Privacy | Mobile
Web03 | 2.8.140421.2 | Last Updated 1 Oct 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid