0

I'm having an issue with my code, and I was hoping you could help! I keep getting a segmentation fault error, and I'm not sure why. I've ran valgrind and according to its findings, the issue seems to be with my fwrite() function but I can't figure it out. Any help would be great, thanks!

#include <stdio.h>
#include <stdlib.h>
#define SIZE 512

int main(int argc, char *argv[])
{
    //if there is not exactly 1 cl argument, it won't work
if(argc != 2)
{
    printf("UNABLE TO COMPLY. FILENAME REQUIRED AT START\n");
    return 1;
}

//START OF PROGRAM WITH VALID USER INPUT
if(argc == 2)
{
    //open input file
    char* input = argv[1];
    FILE* card = fopen(input, "r");
    //check if input is null
    if(card == NULL)
    {
        printf("NO\n");
        return 2;
    }
    //necessary components
    unsigned char check[SIZE];q
    int fileno = 0;
    char filename[9];
    FILE* img = NULL;

    //read the check array 512 bytes at a time
       while(!feof(card) && fread(check, SIZE, 1, card) == 1)
       {
        if(check[0] == 0xff && check[1] == 0xd8 && check[2] == 0xff && ((check[3] & 0xf0) == 0xe0) && fileno == 0)
        {
            
           sprintf(filename, "%03i.jpeg", fileno);
            img = fopen(filename, "w");
            fwrite(check, 1, SIZE, img);
            fileno++;
        }
        else if(check[0] == 0xff && check[1] == 0xd8 && check[2] == 0xff && ((check[3] & 0xf0) == 0xe0) && fileno !=0)
        {
            fclose(img);
            sprintf(filename, "%03i.jpeg", fileno);
            img = fopen(filename, "w");
            fwrite(check, 1, SIZE, img);
            fileno++;
        }
        else
        {
            fwrite(check, 1, SIZE, img);
        }
       
    }
    fclose(card);
    fclose(img);
    return 0;
}
}
1

Question: Assume that the first 512 byte block is being processed. It doesn't have a signature. No output file has been opened yet. What happens when the code drops down to the else clause that says write the block to the output file (that hasn't been opened yet)? Maybe there should be a check to see if the file is actually open?

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

| improve this answer | |
  • Thank you a ton! It worked perfectly! – adfelly Aug 15 at 19:24

You must log in to answer this question.

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