I've been writing this code for a simple server and am having problems. It says there is something wrong with the way I declared my for loops. I looked at some code I had written previously, and the only difference was the variable I placed in the comparison. here is the portion of the code with the for loops.
Code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#define BUFFERSIZE 2048
struct connectInfo{
int connection;
char* root;
};
void handleConnection(void *v) {
struct connectInfo ci = *((struct connectInfo*)v);
int connection=ci.connection;
char* root=ci.root;
free(v);
struct stat statbuf;
printf("Connection open, using file descriptor %d\n", connection);
// Create a file using the file descriptor
FILE *incomingConnection = fdopen(connection, "r");
FILE *outgoingConnection = fdopen(connection, "w");
if (incomingConnection == NULL || outgoingConnection == NULL) {
fprintf(stderr, "Error opening file\n");
exit(1);
}
setlinebuf(outgoingConnection);
char buffer[BUFFERSIZE];
while (fgets(buffer, BUFFERSIZE, incomingConnection) != NULL) {
char* end=fgets(buffer, BUFFERSIZE, incomingConnection);
int fd=open(end, O_RDONLY, 0);
time_t timer=time(NULL);
if (errno==0){
size_t length= (intmax_t)statbuf.st_size;
printf("HTTP/1.1 200 OK \n Date:%s \n Server:myServer version 1.1 \n Last-Modified: %s \n Content-Length: %d \n Connection: close\nContent-Type:text/html\n\n",asctime(localtime(&timer)), (intmax_t) statbuf.st_mtime, (intmax_t)statbuf.st_size);
buffer[0]='\0';
size_t bytes_printed=0;
while (bytes_printed!=length){
read(fd, buffer, BUFFERSIZE);
for (int i=0; i<BUFFERSIZE; i++){
printf("%c", buffer[i]);
}
}
close(fd);
if errno != 0{
printf("An error has occurred while closing %s \n", errno)
}
}
else{
chdir("/home/student/m/marescal/Desktop");
int fd=open("page_404", O_RDONLY, 0);
printf("HTTP /1.1 404 Not Found\nDate: %s \nServer: myServer version 1.1\n Content-Length: %d\nConnection:clos\nContent-Type: text/html\n\n",asctime(localtime(&timer)), (intmax_t)statbuf.st_size);
read(fd, buffer, BUFFERSIZE);
for(int i=0; i<BUFFERSIZE; i++){
if (buffer[i])!=='\0'{
printf("%c", buffer(i));
}
}
close(fd);
}
//... more code