This is how my loop looks now, what have I done wrong? // Read each 512 bytes until end of file is reached FILE* img = NULL; while (fread(&data, 512, 1, diskptr) == 1) { // Check for jpeg start if (checkStart(data, jStart, jStartOE) == true) { jFound++; if (jFound == 1) { // Name and open the first jpeg file char title[12]; sprintf(title, "%03d.jpg", jFound - 1); FILE* img = fopen(title, "w"); fwrite(&data, 512, 1, img); } else { // Close old file fclose(img); // Open new file char title[12]; sprintf(title, "%03d.jpg", jFound - 1); FILE* img = fopen(title, "w"); fwrite(&data, 512, 1, img); } } else if (jFound > 1) { fwrite(&data, 512, 1, img); } } fclose(img); fclose(diskptr);