This while loop is in server program and read call is linked to client via connfd which passes buff as name of file taken fom user via gets and passed through write call. if i paste "filename.txt" in fopen 1st argument it works but this buff as an argument causes fopen to report error as "No such file or directory". :( any help appriciated
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))
Let's assume that read
returns a positive value and buff
is a static char array (char buff[N]
), then you have a char array filled with some data but not a null-terminated string. In order to pass buff
to fopen
you have to append a '\0'
at the end of the data in the buffer buff
.
For that you need the result of read
ssize_t bytes_read = read(connfd, buff, sizeof(buff) - 1); //1 byte for '\0'
buff[bytes_read] = '\0'; //if bytes_read >= 0
After that, if you need the length of the string/data then you have to use strlen(buff)
. Since there could be fewer characters in the buffer than the buffers size (sizeof(buff) != strlen(buff)
).