我正在编写一个简单的程序来将文件从一个点传输到另一个点。应用程序应显示选项
1.列出文件
2.下载文件
3.上传文件
但是一旦我选择了选项1.它列出了目录的内容,我一个接一个地发送文件名但是所有的名字都出现在客户端的一行中。无法弄清楚为什么......
然后它被卡在标记的循环中,一旦recv完成它就会出现循环,它应该再次出现操作选项。我不确定问题是什么。 这是我的代码..
while(1){
//receive chosen option to be performed
if((rdata = recv(clnt, &x, sizeof(int), 0)) > 0){
opt = ntohl(x);
switch(opt){ //switch option and operate
case 1 : //option 1- transfer contents of the directory
if((dr = opendir(".")) != NULL){
while((de = readdir(dr)) != NULL){ //open directory
sprintf(filename, "%s",de->d_name);
rdata = send(clnt, filename, strlen(filename), 0); //transfer filenames
}
}
break;
}
while(1){ //this loop should continue after performing one option
printf("1. List available files on the server\n");
printf("2. Download a file\n");
printf("3. Upload a file to the server\n");
scanf("%d", &opt); //enter desired option
x = htonl(opt); //convert to network byte order
if(send(sockfd, &x, sizeof(int), 0) < 0){ //send option
perror("client: send");
continue;
}
switch(opt){
case 1 :
/************************************************************************/
while((rdata = recv(sockfd, filename, sizeof(filename), 0)) > 0){
filename[rdata] = '\0';
printf("> %s\n", filename);
}
/***********************************************************************/
break;
}
}
答案 0 :(得分:0)
至少据我所知,你想循环直到执行正确的操作(在这种情况下为1,2或3)。如果它是程序应该退出。
int loop = 1;
while(loop){
loop = 0;
printf("1. List available files on the server\n");
printf("2. Download a file\n");
printf("3. Upload a file to the server\n");
scanf("%d", &opt);
x = htonl(opt);
if(send(sockfd, &x, sizeof(int), 0) < 0){
perror("client: send");
continue;
}
switch(opt){
case 1 :
while((rdata = recv(sockfd, filename, sizeof(filename), 0)) > 0){
filename[rdata] = '\0';
printf("> %s\n", filename);
}
break;
default:
loop = 1;
break;
}
}
或者你想循环直到选择退出
int loop = 1;
while(loop){
printf("1. List available files on the server\n");
printf("2. Download a file\n");
printf("3. Upload a file to the server\n");
printf("4. Exir\n");
scanf("%d", &opt);
x = htonl(opt);
if(send(sockfd, &x, sizeof(int), 0) < 0){
perror("client: send");
continue;
}
switch(opt){
case 1 :
while((rdata = recv(sockfd, filename, sizeof(filename), 0)) > 0){
filename[rdata] = '\0';
printf("> %s\n", filename);
}
break;
case 4:
loop = 0;
break;
default:
break;
}
}