简体   繁体   中英

C File reading doesn't stop

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;
}

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 ie returned a value not -1 and 1 otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM