user5859747
user5859747

Reputation:

open() file does not exists when file actually exists

I'm writing a simple HTTP server and I'm getting a file does not exists return value when the file does exist

printf("%s\n", html_path);
if ((fd = open(html_path, "r")) >= 0){ //file found

  stat(file_name, &st);
  file_size = st.st_size;
  printf("%d\n", file_size);
  while (read(fd, response, RCVBUFSIZE) > 0){

  }
}
else { //file not found
    strcpy(response, "404 File not found\n");
    send(clntSocket, response, 32, 0);
}

the print statement is to verify the path and it looks like this:

/mounts/u-zon-d2/ugrad/kmwe236/HTML/index.html

note that this path is on a server that we use at our university. it's the path that shows when I command pwd

I have confirmed that the file exists. is there something wrong with my path?

Upvotes: 1

Views: 2783

Answers (3)

jigglypuff
jigglypuff

Reputation: 527

You need to check where you program is executing as it will try to open the path relative from that location. To check use:

char cwd[1024];
getcwd(cwd, sizeof(cwd));
puts(cwd);

Then you can concatenate your path using:

strncat(cwd, html_path, 100);

You may find that you have to go up one directory or something to then find the file you're looking for.

Also note that if you're debugging your program via gdb it may execute from a different location from your regular build location which may make it harder to spot bugs.

Upvotes: 0

dbush
dbush

Reputation: 223689

There was an error opening the file, but you don't know that it was because the file was not found because you're didn't check the value of errno.

In the else section, add the following:

else { //file not found
    // copy the value of errno since other function calls may change its value
    int err = errno;
    if (err == ENOENT) {
        strcpy(response, "404 File not found\n");
        send(clntSocket, response, 32, 0);
    } else {
        printf("file open failed: error code %d: %s\n", err, strerror(err));
    }
}

If the file does not in fact exist you'll handle the error properly. If not, you'll print an error message that tells you what did happen.

You're also calling open incorrectly. The second parameter is an int containing flags. To open a file for reading, use O_RDONLY.

Upvotes: 2

chris01
chris01

Reputation: 12311

open does not have the 2nd parameter as a string. You using open with the parameters of fopen. For a webserver fopen, fprintf, fclose is a better choise then more lowlevel open, read, ...

Cheers, Chris

Upvotes: 1

Related Questions