reading char types from a string and assigning their numeric value to an int type struct member

时间:2015-11-12 10:55:18

标签: c

I am working on the header file of an audio file in C.

While trying to extract the values chunk by chunk and assign to members of a struct (which are the attributes of the header file in different data type) I faced a problem of not getting the values but the address of the data. It works for char types but not for int types. I have tried sscanf, atoi, and type casting. Unfortunately it didn't work for me. Maybe I am missing a silly thing. My code roughly seems as follow as:

struct wav_header {
               char chunkID[4];
               int chunkSize;}sound_header;

enum {SUCCESS, FAIL};

void writeToStruct(FILE *wavin);

main(void){          
FILE *wptr1;
int ret = SUCCESS; 
char wavContent1[]="sound.wav";// this is the sound wave i am extracting

if ((wptr1 = fopen(wavContent1, "r")) == NULL){
      printf("Cannot open");
      ret = FAIL;
       }
else {      
  writeToStruct(wptr1);
  fclose(wptr1);
      }   
return ret;
}

void writeToStruct(FILE *wavin){
  int i=0,chunkByte[]={4,4,4,4,4,2,2,4,4,2,2,4,4};
  char buff[5];
  long offset=0;

 while (!feof(wavin)&& offset<44){                
     int num = fread(buff, sizeof(char), chunkByte[i], wavin);
     buff[num * sizeof(char)] = '\0'; 

     switch(i){
       case 0:strncpy(sound_header.chunkID,buff,chunkByte[i]);
              printf("chunkID--- %s\n",&sound_header.chunkID);
              break;
       case 1:strncpy(temp,buff,chunkByte[i]); 
              sscanf(temp,"%x",x);
              sound_header.chunkSize=x;     
              printf("\nchunkSize --- %x\n",sound_header.chunkSize);
              break;           
       default: printf("error: out of range");
           } 
 offset=offset+chunkByte[i++];
   }
 } 

(case 0 works correctly as i am assigning a char type from buffer buff to a char type member of the struct)

(case 1 doesn't type from the work as I am trying to assign the char temporary buffer to an int type struct member ). sscanf() and atoi() say to be deprecated. Can somebody help me giving insight?

it just returns null while it should have returned B4B320. Also note: chunkbyte[] is my size specifier array.

1 个答案:

答案 0 :(得分:0)

分配给整数结构成员的情况可以通过声明一个新指针,int * temp和使用memcpy()来修复,如下所示     case 1:temp =&amp; sound_header.chunkSize;            的memcpy(温度,浅黄色,chunkByte [I]);            的printf(&#34; CHUNKSIZE ---%×\ n&#34;,sound_header.chunkSize);            打破; 这还需要纠正字节顺序,因为我的笔记本电脑有一个小端架构,它以两个字节数的相反顺序给出。它也没有保留空值