2016-07-24 8 views
0

私はcs50からこの問題を設定するためにいくつかの助けをすることができました。私のコードがwhileループに当たると、fread関数は0を返します。なぜこれが起こるのか分かりません。私がこの問題に遭遇する前でさえ、私のコードは私が望むように動作していなかったので、追加のヒントがあれば本当に役に立ちます。pset4 cs50 recover.cガイダンス

#include <stdio.h> 
#include <stdlib.h> 
#include <stdint.h> 
#include <stdbool.h> 

//PROTOTYPES 
bool check(uint8_t block[]); 

int main(int argc, char* argv[]) 
{ 
    FILE* inptr = fopen("card.raw", "r"); //open up the card.raw file for reading 

    if(inptr == NULL) 
    { 
     fclose(inptr); 
     printf("Could not open the card data.\n"); 
     return 1; 
    } 

    FILE* outptr; 

    int jpegCount = 0; 
    bool foundFirstJpg = false;// flag to denote wheather the first jpg has been found 

    char str[10]; //to hold the jpg name 
    sprintf(str, "%i.jpg", jpegCount); //puts the image name in str 
    jpegCount ++; 
    outptr = fopen(str, "w"); //Create a new jpeg for each image 

    uint8_t block[512]; // a tempory block to hold 512 bytes of info 

    while(fread(block, sizeof(block), 1, inptr) == 1) //read 512 bytes of info at a time from the inptr) 
    { 
     printf("hello\n"); 
     if(check(block)) //if I have found a jpg 
     { 
      if(foundFirstJpg) //if its not my first jpg 
      { 
       fclose(outptr); //close the previous jpg file 
       sprintf(str, "%i.jpg", jpegCount); //puts the image name in str 
       outptr = fopen(str, "w"); //Create a new jpeg for each image 
       jpegCount ++; 
       fwrite(block, sizeof(block), 1, outptr); //write the block to the image file 
      } 
      else 
      { 
       fwrite(block, sizeof(block), 1, outptr); //write first block to the image file 
       foundFirstJpg = true; 
      } 
     } 
     else //if this is not a jpg 
     { 
      if(foundFirstJpg) //check if we have found our first jpg 
      { 
       fwrite(block, sizeof(block), 1, outptr); //write 512 bytes to the current image file 
      } 
     } 
    } 
    if (outptr) 
    { 
     fclose(outptr); 
    } 
    fclose(inptr); 
    return 0; 
} 

//function to check if this is the start or end of a jpg 
bool check(uint8_t block[]) 
{ 
    bool isJpg = true; //boolean value to be returned 
    if (block[0] != 0xff || block[1] != 0xd8 || block[2] != 0xff) //checks if the first 3 bytes are those that represent a jpg 
    { 
     isJpg = false; 
    } 
    if (block[3] < 0xe0 || block[3] > 0xef) //checks if the fourth byte also represents a jpg 
    { 
     isJpg = false; 
    } 
    return isJpg; 
} 

答えて

0

あなたはバイナリモードでこれらのファイルを開くshoud:

FILE *inptr = fopen("card.raw", "rb"); 
... 
outptr = fopen(str, "wb"); 

card.rawが512バイト未満を持っている場合は、fread0を返します。

+0

残念ながら、それは私の問題を解決しませんでした。あなたの提案をありがとうtho。 – SillyRab

+0

また、 'xxd -l 2400 card.raw'を実行してcard.rawからいくつかのバイトを読み込んで何かを得ることができるかどうかを確認するために実行します。何も表示されません。私のコマンドラインは次の行に移動します。 – SillyRab

+0

'card.raw'ファイルのコピーがなければ何が起こっているのかを知ることは難しいです。 – chqrlie

関連する問題