1

I have a server.conf file, that contains the path to an html.file, with a simple paragraph in it.

I program with a function readFile() that is supposed to take in a file path and return its contents. (The 3 mentioned files are in the same folder).

When I pass in the first file path (server.conf) it works, and the path "index.html" gets returned.

However, when I try to use the same method to read the path that its returned the first time, the file pointer in readFile() is 'nil' after the fopen() file is called.

Any help on why this is happening would be much appreciated.

  1. The main program:
#include <string.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define MAX_BUFFER      1024


char *readFile(char *filePath){
    
    FILE* fp = malloc(MAX_BUFFER);  
    char* fileContent = malloc(MAX_BUFFER);
    
    fp = fopen(filePath, "r");  
        printf("filepath is: %s\n", filePath);
        printf("pointer is: %p\n", fp);

    
    if (NULL == fp) {
        printf("file can't be opened \n");
    }
    
    while (fgets(fileContent, MAX_BUFFER, fp) != NULL) {
        printf("content of fileContent in readFile: %s\n", fileContent);
    }
     
    fclose(fp);
    
    return fileContent;
}


int main ( void )
{
    char *serverConfContent;
    serverConfContent = readFile("server.conf");
    
    char *htmlContent = readFile(serverConfContent);

}

  1. server.conf:
index.html
  1. index.html:
<html><head><p>This is an example paragraph.</p></html>
OcR19
  • 23
  • 4
  • 1
    `FILE* fp = malloc(MAX_BUFFER);` is a memory leak – Mad Physicist Aug 05 '22 at 14:57
  • Remove `= malloc(MAX_BUFFER)` after `FILE *fp`, it has no purpose at all. – Jabberwocky Aug 05 '22 at 15:00
  • 2
    `fgets` puts the newline character into the buffer, so the filename is `index.html\n`. [See this question](https://stackoverflow.com/questions/2693776) which explains how to remove the newline. – user3386109 Aug 05 '22 at 15:01
  • 2
    You almost certainly have a newline at the end of the file. When you do debugging of strings, add some delimiter characters around the string to make sure you catch whitespace. – Mad Physicist Aug 05 '22 at 15:02
  • 1
    Also: if `fp` is NULL you printf `file can't be opened`, but what happens then? Think about it. – Jabberwocky Aug 05 '22 at 15:03
  • you are right, thank you... this was one of my attempts to try to make it work. before I had declared simply FILE* fp; but I was still getting the same error. – OcR19 Aug 05 '22 at 15:05
  • remove as suggest the /n int main ( void ) { char *serverConfContent; serverConfContent = readFile("server.conf"); strtok(serverConfContent, "\n"); char *htmlContent = readFile(serverConfContent); } – Mariano Aug 05 '22 at 15:13
  • "file can't be opened" is not a useful error message, and error messages belong on stderr: `if( (fp = fopen(filePath, "r")) == NULL ){ perror(filePath); exit(1); }` – William Pursell Aug 05 '22 at 15:42

0 Answers0