【问题标题】:Printing components of structure gives weird repetitions打印结构组件会产生奇怪的重复
【发布时间】:2023-04-03 07:35:02
【问题描述】:

我试图打印出结构中的元素(.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{ 字符 RIFF[4]; 整数块大小; 字符波[4]; 字符 fmt[4]; };

【问题讨论】:

  • 你没有发布struct WAV的定义,也没有投malloc()

标签: c


【解决方案1】:

您的printf() 调用正在打印字符串。但是您的fscanf() 调用正在读取chars,它们不是以空结尾的,因此不是字符串。

【讨论】:

  • 是的,你是对的。我在看到包含 wav 结构的更新之前发布了该内容。错误地假设缓冲区更大。但关键点是正确的——尝试用 char 数组打印字符串。
【解决方案2】:

带有"%s" 说明符的*printf() 函数需要一个字符串,它在c 中需要一个终止'\0' 字节,而您的数组没有。

你可以这样做

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

相反,然后您将打印要打印的确切字符数,这不会强制您修改数据。

【讨论】:

  • 感谢它的工作!所以现在如果我想打印出 WAV 结构的所有元素,我是否必须为结构的每个元素写两行?
  • 如果内容不是字符串,你可以为此编写一个函数。
【解决方案3】:

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);

【讨论】:

    猜你喜欢
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    相关资源
    最近更新 更多