ff210327
ff210327

Reputation: 15

Read file and send across a socket connection not looping

I am trying to open a file, read it in, and then send it line by line across a socket connection to a waiting client. The issue i'm getting is for some reason the loop isn't working, it will only send the first line of the file each time I touch off the "LIST" command.

                   else if (cmd.compare(list) ==0) /* LIST user input */
                    {
                        file_ptr = fopen("file1.txt", "r");

                        while (fgets(buf, sizeof(buf), file_ptr) != NULL) {

                                    {

                                    while(!feof(file_ptr))
                                    send (new_s, buf, strlen(buf) + 1, 0);
                                    printf("%s",buf);
                                }


                    }

                            fclose(file_ptr);
                    }

Can anyone see what i'm doing wrong?

Output from the "LIST" command on the client side (LIST was typed each time in order to get these results)

LIST

ECHO:matthew funk 3123214321

LIST

ECHO:3123214321

LIST

ECHO:tthew funk 3123214321

LIST

ECHO:23214321

LIST

ECHO:hew funk 3123214321

LIST

ECHO:214321

LIST

ECHO:w funk 3123214321

LIST

ECHO:4321

LIST

ECHO:funk 3123214321

^C

Contents of the file being read in

"file1.txt" 12L, 399Cc

matthew funk 3123214321

1000Jonny Applesee7655431234

1001Billy Joel 7312431234

1002Billy Idol 123456789

1003Jean Doe 9876543211

1000 peauntbuJelly 123456789

1001 mother THreasea987654321

1000 peter paul and

1000 COmputernetworki12341234123

1001 COmputernetworki12341234123

1002 COmputernetworki12341234123

1003 COmputernetworki12341234123

Upvotes: 1

Views: 78

Answers (1)

user207421
user207421

Reputation: 311039

while (fgets(buf, sizeof(buf), file_ptr) != NULL) {
{
    while(!feof(file_ptr))
        send (new_s, buf, strlen(buf) + 1, 0);
    printf("%s",buf);
}

The while (!feof(file_ptr)) loop is pointless. You're sending the same thing over and over again until feof() occurs, which it never will because you aren't reading from the file. And you already have a test for EOF in the form of the prior != NULL.

I wouldn't use fgets() for this, or strlen() either. There's no need to make assumptions about the data. In this case you're assuming it's text with no embedded nulls. All you need is this:

size_t count;
while ((count = fread(buf, 1, sizeof buf, file_ptr)) > 0)
{
    send(new_s, buf, count, 0);
}

As a matter of fact I wouldn't use stdio for this either, just open(), read(), and close() ...

Upvotes: 1

Related Questions