这个while循环在服务器程序中,读取调用通过connfd链接到客户端,connfd通过get将buff作为文件名传递给用户,并通过写入调用传递。如果我粘贴";filename.txt";在fopen第一个参数中它起作用,但是这个buff作为参数导致fopen报告错误为"0";没有这样的文件或目录":(任何帮助通知
while(read(connfd, buff, sizeof(buff))){
write(1, buff, sizeof(buff));
if((fp = fopen(buff, "r")) == NULL){
perror("File Open error");
write(connfd, "File Open error! File not found", sizeof("File Open error! File not found"));
}else{
send_file(fp, connfd);
printf("nFile sent Successfully! in server_helper");
}
bzero(buff, sizeof(buff));
}
read(connfd, buff, sizeof(buff))
假设read
返回一个正值,而buff
是一个静态的char数组(char buff[N]
(,那么您有一个char数组,其中填充了一些数据,但没有以null结尾的字符串。为了将buff
传递给fopen
,您必须在缓冲区buff
中的数据末尾附加一个' '
。
为此,您需要读取的结果
ssize_t bytes_read = read(connfd, buff, sizeof(buff) - 1); //1 byte for ' '
buff[bytes_read] = ' '; //if bytes_read >= 0
之后,如果您需要字符串/数据的长度,则必须使用strlen(buff)
。由于缓冲区中的字符可能少于缓冲区大小(sizeof(buff) != strlen(buff)
(。
我得到了感谢@Erdal KüçüK我使用了strlen作为sizeof来提供完整的buff,我只需要有数据的部分,而不是所有的
while(read(connfd, buff, sizeof(buff) - 1)){
int len = strlen(buff);
printf("%d",len);
buff[strlen(buff) - 1] = ' ';
write(1, buff, sizeof(buff));
if((fp = fopen(buff, "r")) == NULL){
perror("File Open error");
write(connfd, "File Open error! File not found", sizeof("File Open error! File not found"));
}else{
send_file(fp, connfd);
printf("nFile sent Successfully! in server_helper");
}
bzero(buff, sizeof(buff));
}