I'm trying to use an iterative loop to read the first 512 byes for comparison in pset4 recover.c. This makes sense to me. Unfortunately the computer doesn't feel same

typedef int32_t  LONG;
typedef uint8_t  BYTE;

int main(void)
    FILE* file = fopen("card.raw", "r");
    if (file == NULL)
        printf("file couldn't be recovered");
        return 2;

    LONG id;
    int n = 512;
    LONG first[n];
    while (!feof(file))
        for (int i = 0; i < n; i++)
            fread(&id, 1, 1, file);
            first[i] = id;
            fseek(file, 1, SEEK_CUR);
        if (first[0] == 0xff && first[1] == 0xd8 && first[2] == 0xff && (first[3] == 0xe0||first[3] == 0xe1) )
            return 0;
            printf("not working\n");

There are a number of issues with the code. First, there is already a 32 bit signed integer type called long, so there's no need to typedef a new one.

The first[] array is declared as 512 elements of type LONG. That's 512 * 8 = 4096 bytes. An unsigned 1-byte type is a better choice, like uint8_t.

In the first for loop, the code reads 1 byte into a 4 byte signed variable on each pass. But then, it has an fseek that will move the file pointer forward and skip over data. Note that an fread call will move the file pointer past whatever is read and leave it at the first unread byte past the read.

Finally, consider this. The resources required to read 1 byte from the file are the same as it takes to read 512 bytes. This is because about 95% of the resources for a disk read are overhead, not the actual read. By comparison, it takes a lot of time to spin the disk and position the read/write head over the right track vs. actually reading a disk data block, which will be on the order of 4k. (Any read or write will process a full data block, defined by the disk configuration, usually 4k, even if you are reading 1 byte.) So, it's far more efficient to read in the entire 512 bytes and then manipulate the data in memory. Disk operations take about 1000 times longer than memory operations.

This should give you something to think about as you redesign your code. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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