I wrote a simple http server in C and I was now trying to send html responses. I wrote a function to read the html file and put it in a string but turns out it’s only working on small .txt files.
I was getting seg faults every time I try to read an html file.
Here’s my code:
int file_to_str(char** string, char* filename){
FILE* mystream = fopen(filename, "r");
char c;
int index = 0;
*string = (char*) malloc(sizeof mystream);
while ((c = getc(mystream)) != EOF){
if (c == '"') c = ''';
(*string)[index++] = c;
}
fclose(mystream);
//string will be freed by the caller
}
2
Answers
You probably are experiencing buffer overrun, unless you happen to read a file smaller than the buffer malloc returns (it can be internally larger than what you request)
Try the following:
Also note: if you aren’t going to return anything, then your return type should be void. Otherwise, you should return a value, maybe the char count? And I used malloc in keeping with your code, but consider an STL container.
FYI: Be careful. Your question has a negative score. I’m afraid to ask another question because they ban users with low scores, and this is a great research space. I think your question is valid and I want to help you, but I just want you to be aware.