Thread: sockets and fputs

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    58

    sockets and fputs

    Hi All;

    I have a problem here. I have a file and i used fgets to read a line from the file and when i print it out its grand. So when i try to use this with sockets i hit a problem.

    I fget into an array and then write it to the socket eg
    write(sockfd, buffer 255);


    So when my server receives this, and the code goes like this
    Code:
    char buffer[256];
    read(sock, buffer, 256);
    fputs(buffer, stdout);

    I get what i sent over but alot of rubbish is printed out after it. I think its printing out my string and the remainer of the buffer. Am i right in this thinking abd how do i solve the problem and why does it occur when transporting over the socket?

    Should i use strlen(buffer) instead of the size of 256?

    THanks

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    If you just want to send the string, then this makes more sense:
    Code:
    write(sockfd, buffer strlen(buffer)+1);
    This way you send just the string and the null terminator.
    bit∙hub [bit-huhb] n. A source and destination for information.

  3. #3
    Registered User
    Join Date
    Aug 2009
    Posts
    58
    Thats what i thought, my mistake was instead of use strlen i included value 256 and which would cause rubbish to be printed after a string that was 10 chars long. Thats right isnt it?

  4. #4
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Well, if there was a null terminating character after the 10 string chars, then there shouldn't be any rubbish printed. fputs will print characters until it finds the null terminator.
    bit∙hub [bit-huhb] n. A source and destination for information.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sockets( ) programming
    By xlordt in forum Networking/Device Communication
    Replies: 7
    Last Post: 09-23-2003, 09:26 PM