0

I'm not sure if what I did makes sense but here's the code for the load function:

if (file != NULL) {
    char c;
    int counter = 0;
    while ((c = fgetc(file)) != EOF) {
        counter++;
    }

    char* fileContent = malloc((counter + 1) * sizeof(char));
    counter = 0;
    rewind(file);
    while ((c = fgetc(file)) != EOF) {
        fileContent[counter] = c;
        counter++;
    }

    *content = fileContent;
    *length = counter;

    return true;
}
return false;

When I test it with HTML files, it works, but not with PHP or JPG. Help?

1

I couldn't have said it better myself. From this SE post:

rewind is equivalent to fseek(stream, 0L, SEEK_SET) and fseek is only legal on files, not streams (which is the case with pipes).

From pset instructions:

Odds are you’re unfamiliar with popen. That function opens a "pipe" to a process (php-cgi in our case),

This explains the problem with php, though not necessarily with jpg. If you get familiar with realloc, you should be able to do this routine with one loop, thus avoiding the rewind.

Wait, I see the problem with jpg, it's this char c; declaration. Because of internal casting in fgetc, this can return a "false eof", and almost always does on binary (image) files. Some char in the image files is being cast to the int -1. EOF is defined (in stdio.h) as -1. The loop ends prematurely. If you cast c as an int (instead of char), it should work. This article may help clarify the point.

1
  • Thank you, I just fixed the JPG part. Now I'll give realloc() a shot. Thanks once again :-)
    – Omar
    Aug 6 '16 at 15:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .