Winsock/ofstream trouble

This is a discussion on Winsock/ofstream trouble within the C++ Programming forums, part of the General Programming Boards category; I have my basic socket program I got from another post, since I'm really a sockets beginner. Here's the code. ...

  1. #1
    Programming is fun, mkay?
    Join Date
    Oct 2001
    Posts
    490

    Question 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?

  2. #2
    Registered User
    Join Date
    Dec 2001
    Posts
    194
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trouble with assignment in C
    By mohanlon in forum C Programming
    Replies: 17
    Last Post: 06-23-2009, 11:44 AM
  2. Replies: 6
    Last Post: 01-03-2007, 03:02 PM
  3. Is it so trouble?
    By Yumin in forum Tech Board
    Replies: 4
    Last Post: 01-30-2006, 04:10 PM
  4. trouble scanning in... and link listing
    By panfilero in forum C Programming
    Replies: 14
    Last Post: 11-21-2005, 12:58 PM
  5. C++ program trouble
    By senrab in forum C++ Programming
    Replies: 7
    Last Post: 04-30-2003, 12:55 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21