我正在尝试打印出结构中的元素(.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


该结构如下所示:
    结构wav_t {
        char RIFF [4];
        int ChunkSize;
        char WAVE [4];
        char fmt [4];
    };

最佳答案

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

关于c - 打印结构部件产生奇怪的重复,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29596486/

10-12 14:51
查看更多