2015-04-13 67 views
0

我試圖打印結構中的元素(.WAV文件頭)。我已經實現了endian校正功能。但是,當我做printf時,它顯示了一個奇怪的元素重複。誰能幫忙?打印組件的結構給出奇怪的重複

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 

#include "prog9.h" 

/* 
* little_endian_2 - reads 2 bytes of little endian and reorganizes it into big endian 
* INPUTS:  fptr - pointer to the wav file 
* OUTPUTS:  none 
* RETURNS:  the data that is converted to big endian 
*/ 
int little_endian_2(FILE *fptr) 
{ 
    int count; 
    char temp[2]; 

    fscanf (fptr, "%2c",temp); 


    char holder; 

    holder = temp[1]; 
    temp[1] = temp[0]; 
    temp[0] = holder; 

    count = atoi(temp); 
    return count; 
} 

/* 
* little_endian_4 - reads 4 bytes of little endian and reorganizes it into big endian 
* INPUTS:  fptr - pointer to the wav file 
* OUTPUTS:  none 
* RETURNS:  the data that is converted to big endian 
*/ 
int little_endian_4(FILE *fptr) 
{ 
    char temp[4]; 

    fscanf (fptr, "%4c", temp); 

    int final = *(int *)temp; 

    //printf ("%i\n",final); 

    return final; 
} 

/* 
* read_file - read the wav file and fill out the wav file struct 
* INPUTS:  wavfile - a string that contains the name of the file 
* OUTPUTS:  none 
* RETURNS:  the pointer to the wav file struct created in this function 
* SIDE EFFECT: prints the information stored in the wav struct 
*/ 
WAV *read_file(char *wavfile) 
{ 
    WAV* wav_ptr = (WAV*)malloc(sizeof(WAV)); 

    FILE *fp; 
    fp = fopen(wavfile,"r"); 

    fscanf (fp, "%4c", wav_ptr->RIFF); //For RIFF 

    wav_ptr->ChunkSize = little_endian_4(fp); 

    fscanf (fp, "%4c", wav_ptr->WAVE); //For WAVE 

    fscanf (fp, "%4c", wav_ptr->fmt); //For fmt 

    printf("%s\n", wav_ptr->RIFF); 
    printf("%i \n", wav_ptr->ChunkSize); 
    printf("%s \n", wav_ptr->WAVE); 
    printf("%s \n", wav_ptr->fmt); 
    return wav_ptr; 

} 

運行後,它將打印到輸出。

RIFFvu 
882038 
WAVEfmt 
fmt 

的結構是這樣的: 結構wav_t { 炭RIFF [4]; int ChunkSize; char WAVE [4]; char fmt [4]; };

+2

你沒有張貼的'結構WAV'的定義,不投'的malloc()'。 –

回答

1

您的printf()呼叫是打印字符串。但您的fscanf()調用讀取的是char s,它們不是空終止的,因此不是字符串。

+0

是的,你是對的。我發佈之前看到更新包括wav結構。錯誤地認爲緩衝區較大。但關鍵點是正確的 - 試圖用char數組打印字符串。 – kaylum

0

*printf()函數"%s"說明符期望一個字符串,其中c需要終止字節,您的數組不具有。

你可以做到這一點

fwrite(wav_ptr->RIFF, 1, 4, stdout); 
fprintf(stdout, "\n"); 

代替,然後將打印要打印字符的確切數目,不會強迫你修改數據。

+0

感謝它的工作!所以現在如果我想打印出WAV結構的所有元素,我是否必須爲結構的每個元素寫兩行? – bearswithattitude

+0

那麼如果內容不是字符串,你可以寫一個函數。 –

0

printf("%s", ...)想要打印NUL終止的字符串,但是您的字符串不是NUL終止的。您可以使用一個明確的最大長度,限制大小和避免對NUL終止的需要:

printf("%.4s\n", wav_ptr->RIFF); 
printf("%i \n", wav_ptr->ChunkSize); 
printf("%.4s \n", wav_ptr->WAVE); 
printf("%.4s \n", wav_ptr->fmt);