Reputation: 899
I am writing a simple server that allows sending files using HTTP protocol. I have a function that puts everything from the file into buffer. Everything goes well before read. The file size is printed correctly. But on read program just waits.
char *get_file(char *dir) {
fprintf(stderr, "GET FILE\n");
char *buff;
int fd;
if (fd = open(dir, O_RDONLY) == -1) {
fprintf(stderr, "No such file: %s\n", dir);
exit(6);
}
size_t size = fsize(dir);
fprintf(stderr, "OPENED FILE, SIZE: %ld\n", size);
buff = malloc(size);
read(fd, buff, size);
fprintf(stderr, "to be downloaded: %s\n", buff);
char *response = make_file_response(buff);
return response;
}
Upvotes: 0
Views: 100
Reputation: 53036
You have an issue with this statement
if (fd = open(dir, O_RDONLY) == -1)
according to operator precendence ==
is evaluated first and thus, fd
is being assigned the value of the comparison and not the opened file descriptor.
With compiler warnings enabled parentheses would be suggested, and the correted expression would be
if ((fd = open(dir, O_RDONLY)) == -1)
/* ^~~~~~~~~~~~~~~~~~~~~~~~~^ */
would first assign the return value of open()
to fd
and then the comparison is performed.
If you print the value of fd
you will see that it's 0
if open()
succeeded i.e. returned a value not -1
and 1
otherwise.
Upvotes: 3