【问题标题】:Why using fread() the 2-nd time it reads a file not from beginning but from the end of reading by the 1-st fread()?为什么第二次使用 fread() 它不是从头开始读取文件,而是从第一次 fread() 读取结束时读取文件?
【发布时间】:2013-05-06 14:13:08
【问题描述】:

我想用来自in.wav 文件的数据填充hdr (struct) 变量,并且我想将in.wav 文件的前64 个字节复制到另一个文件(out.wav)。

但是!当第二次使用fread() 时,它开始从第一次使用fread() 时完成的位置复制in.wav。为什么?

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

typedef struct FMT
{
    char        SubChunk1ID[4];
    int         SubChunk1Size;
    short int   AudioFormat;
    short int   NumChannels;
    int         SampleRate;
    int         ByteRate;
    short int   BlockAlign;
    short int   BitsPerSample;
} fmt;

typedef struct DATA
{
    char        Subchunk2ID[4];
    int         Subchunk2Size;
    int         Data[441000]; // 10 secs of garbage. he-he)
} data;

typedef struct HEADER
{
    char        ChunkID[4];
    int         ChunkSize;
    char        Format[4];
    fmt         S1;
    data        S2;
} header;



int main()
{
    FILE *input = fopen("in.wav", "rb");
    FILE *output = fopen("out.wav", "wb");

    unsigned char buf[64];
    header hdr;

    if(input == NULL)
    {
        printf("Unable to open wave file\n");
        exit(EXIT_FAILURE);
    }

    fread(&hdr, sizeof(char), 64, input);


    fread(&buf, sizeof(char), 64, input);
    fwrite(&buf, sizeof(char), 64, output);


    printf("\n>>> %4.4s", hdr.ChunkID);

    fclose(input);
    fclose(output);

    return 0;
}

怎么了?

【问题讨论】:

  • 为什么你不想从文件中顺序读取?为什么要一遍又一遍地读取相同的数据?
  • fread 从当前文件位置开始读取并将其增加读取的字节数。
  • @SanderDeDycker 第一个用于某些操作(用于操作),第二个用于验证 out.wav 数据(在我重写之后)。
  • @Julian:我说的是另一个fread。在典型使用中,您希望自动更新位置。考虑一下如果该文件大小为 16 GB 会发生什么。你不能一次读完整本书,你也不想每次都去fseek()。 (通常,只有远程甚至关心当前文件位置,更不用说自己跟踪它了。)你是一个半特殊情况,所以你得到额外的工作。 :P
  • C 有效地将文件视为字符流。 (你会看到这个词在标准 I/O 方面被大量使用。)

标签: c file binary-data fread


【解决方案1】:

这是有意的。 fread 总是从文件的当前读取指针中读取并推进相同的指针,因此您可以按顺序块中的文件而无需显式查找。

您不必连续两次读取相同的块。您通过这种方式检查的是其他进程是否同时更改了文件,如果有,那么您的程序将错误地报告复制失败。

【讨论】:

    【解决方案2】:

    文件指针被移动。在此处阅读更多信息:Does fread move the file pointer?。您可以使用 fseek 或 rewind 来定位文件的开头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 2019-04-13
      • 2016-04-20
      • 2014-07-21
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      相关资源
      最近更新 更多