-
Winsock/ofstream trouble
I have my basic socket program I got from another post, since I'm really a sockets beginner. Here's the code. I want it to log all incoming to a file, but it won't do it:
#include <winsock.h>
#include <stdio.h>
#include <fstream.h>
#include <stdlib.h>
int main(int argc, char** argv) {
char pBuf[2048];
int rCount=0;
WSADATA wsaData; WORD version;
SOCKET listeningSocket, theClient;
SOCKADDR_IN saServer; saServer.sin_family = AF_INET;
saServer.sin_addr.s_addr = INADDR_ANY;
saServer.sin_port = htons(5555);
version = MAKEWORD(1,1);
WSAStartup(version, &wsaData);
listeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bind(listeningSocket, (LPSOCKADDR)&saServer, sizeof(struct sockaddr));
listen(listeningSocket, 10);
theClient=INVALID_SOCKET;
while(1){
theClient = accept(listeningSocket,NULL, NULL);
if(theClient!=INVALID_SOCKET)
while(strcmp(pBuf,"end")){
recv(theClient, pBuf, 2048, 0);
printf( "-->%s\n", pBuf);}
ofstream log ("C:\\website\\Log.txt", ios::app);
if( log.is_open() )
{
log << pBuf;
log.close();
}
strcpy(pBuf,"");
theClient = INVALID_SOCKET;
system("PAUSE");}
closesocket(theClient);
closesocket(listeningSocket);
WSACleanup();
return 0;}
It will not create and add to the file. What is wrong?
-
Why not try declairing the ofstream object at the beginning of main. Then open the output file ONCE. Write to it has necessary, then close it at the end of your program.
Does that printf statement print out the correct information?
Also, you may want to write an endl after each line in the output file, so there is some seperation