2016-01-02 54 views
0

我想打開用戶在屏幕上鍵入的bmp文件。我有一個函數,要求圖像名稱和另一個加載BMP圖片:加載BMP文件時出錯C

/************************************************************************** 
    * load image                * 
    * Ask the user for an image file to load into screen.     * 
    **************************************************************************/ 

    void load_image(){ 
     char name[100]; 
     BITMAP image; 
     save_frame_buffer(); 
     set_mode(TEXT_MODE); 
     printf("Enter the name of image (BMP): \n"); 
     fgets(name,100,stdin); 
     set_mode(VGA_256_COLOR_MODE);   
     set_pallete(background.pallete); 
     load_bmp(name,&image); 
     show_buffer(frame_buffer); 
     draw_bitmap(&image,32,0); 

    } 


/************************************************************************** 
* load_bmp                * 
* Loads a bitmap file into memory.         * 
**************************************************************************/ 
void load_bmp(char *file, BITMAP *b){ 

    FILE *fp; 
    long index; 
    word num_colors; 
    int x; 

    /*Trying to open the file*/ 
    if((fp = fopen(file,"rb")) == NULL){ 

     printf("Error opening the file %s.\n",file); 
     exit(1); 
    } 

    /*Valid bitmap*/ 
    if(fgetc(fp) != 'B' || fgetc(fp) != 'M'){ 

     fclose(fp); 
     printf("%s is not a bitmap file. \n", file); 
     exit(1); 

    } 


    /* Read and skip header 
    */ 
    fskip(fp,16); 
    fread(&b->width, sizeof(word),1 , fp); 
    fskip(fp,2); 
    fread(&b->height, sizeof(word),1,fp); 
    fskip(fp,22); 
    fread(&num_colors,sizeof(word),1,fp); 
    fskip(fp,6); 

    /* color number VGA -256 */ 
    if(num_colors ==0) num_colors = 256; 


    /*Allocating memory*/ 
    if((b->data = (byte *) malloc((word)(b->width*b->height))) == NULL) 
    { 
     fclose(fp); 
     printf("Error allocating memory for file %s.\n",file); 
     exit(1); 

    } 

    /*Reading pallete information*/ 
    for(index=0;index<num_colors;index++){ 


     b->pallete[(int)(index*3+2)] = fgetc(fp) >> 2; 
     b->pallete[(int)(index*3+1)] = fgetc(fp) >> 2; 
     b->pallete[(int)(index*3+0)] = fgetc(fp) >> 2; 
     x = fgetc(fp); 

    } 

    /*Reading the bitmap*/ 
    for(index=(b->height-1)*b->width;index>=0;index-=b->width){ 
     for(x=0;x<b->width;x++){ 
      b->data[(word)(index+x)] = (byte) fgetc(fp); 

     } 


    } 
    fclose(fp); 

} 

load_bmp()功能工作正常,因爲從來就成功加載其他圖像。我面臨的問題是輸入。

當我硬編碼的文件名是這樣的:

load_bmp("mainbar.bmp",&image); 

BMP文件被成功加載。但是,如果將name變量放在load_bmp()函數中,我會將fp設置爲NULL

任何人都可以告訴我是什麼導致了這個問題?

+0

這就是我需要的。我沒有閱讀手冊頁,我很抱歉。非常感謝您的幫助。 –

+0

沒問題。對於這種情況,手冊中通常有一個隱藏的寶石。 :)在這種情況下,換行符經常被忽略,所以你並不孤單! – lurker

回答

1

的手冊頁fgets說,尤其是,

讀取EOF或換行後停止。如果讀取換行符,則將其存儲在緩衝區中的爲 。

如果您的name變量以換行符結尾(如果在輸入名稱時按ENTER鍵),它將不匹配文件名。你需要擺脫名稱末尾的換行符。