打印结构组件给出了奇怪的重复

时间:2015-04-13 01:03:45

标签: c

我试图打印出结构中的元素(.WAV文件头)。我已经实现了字节序校正功能。然而,当我做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  

结构看起来像这样:     struct wav_t {         char RIFF [4];         int ChunkSize;         char WAVE [4];         char fmt [4];     };

3 个答案:

答案 0 :(得分:1)

您的printf()来电正在打印字符串。但是你的fscanf()调用正在读取char s,它们不是以空值终止的,因此不是字符串。

答案 1 :(得分:0)

*printf()说明符的"%s"函数需要一个字符串,其中c表示终止'\0'字节,而您的数组不具备该字符串。

你可以这样做

fwrite(wav_ptr->RIFF, 1, 4, stdout);
fprintf(stdout, "\n");
相反,然后您将打印要打印的确切字符数,这不会强制您修改数据。

答案 2 :(得分: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);