Hi i am a newbie in C programming especially in the socket area.
Supposely i am writing a FTP, and want to get and put file in the FTP.
However, i have encountered a bug/error when client is trying to get(download) file from server.
The problem is as follow:
First, client type get test.c
. Then, server will start trasnfer test.c to client.
During the process of receiving test.c, client is actually received the file while he receive the error message at the same time.
Then, when i ls -l
in both side, test.c in client receive some additional byte.
Which when i open the test.c, i found some weird character such as ^@
or space(s) appears at the end of the file.
i have attached a sample screen to better illustrated the situation as well as the portion source code of server & client.
client.c
while (1) {
// get input from user and breaks the 'buf' into 'token[]'
if ((nw = writen(sd, buf, nr)) < nr) { perror("send"); } // write stream
// token[0] = "get"
// token[1] = "test.c"
if (strcmp("get", token[0]) == 0) {
char file[512];
memset(&buf, 0, sizeof (buf));
memset(&file, 0, sizeof (file));
recv(sd, buf, 4096, 0);
// file = "test.c"
strncpy(file, buf, strlen(buf) > 512 ? 512 : strlen(buf));
printf("File '%s' receiving...\n", file);
// write in binary
FILE *fd = fopen(file, "wb+");
memset(&buf, 0, sizeof (buf));
int length = 0;
while ((length = recv(sd, buf, SIZE, 0)) > 0) {
fwrite(buf, sizeof (char), length, fd);
if (strlen(buf) > 0) {
printf("received: %d\n", strlen(buf));
memset(&buf, 0, sizeof (buf));
}
}
printf("File '%s' received.\n", file);
fclose(fd);
if (close(sd) < 0) {
perror("close");
}
}
if ((nr = readn(sd, buf, sizeof (buf))) <= 0) { perror("receive"); } // read stream
buf[nr] = '\0';
}
server.c
while (1) {
if ((nr = readn(sd, buf, sizeof (buf))) <= 0) { return; } // read stream
buf[nr] = '\0';
// token[1] = "test.c"
memset(&buf, 0, sizeof (buf));
strncpy(buf, token[1], strlen(token[1]) > 512 ? 512 : strlen(token[1]));
send(sd, buf, 4096, 0);
FILE *fd = fopen(token[1], "rb+");
printf("\nFile '%s' transferring...\n", token[1]);
memset(&buf, 0, sizeof (buf));
int length = 0, total = 0;
while ((length = fread(buf, sizeof (char), 4096, fd)) > 0) {
printf("Length : '%d'\n", length);
send(sd, buf, length, 0);
memset(&buf, 0, sizeof (buf));
total += length;
}
printf("File '%s' transfered (%d-byte)!\n", token[1], total);
fclose(fd);
nr = strlen(buf);
nw = writen(sd, buf, nr); // write stream
}
Can anyone points out what mistake I've made in the program?
Or perhaps the step or file reading and writing is wrong in sequence?
Or... maybe any other case?
THANKS FOR GUIDING ME and APPRECIATE VERY MUCH = )