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()?

StackOverflow https://stackoverflow.com/questions/16400633

  •  14-04-2022
  •  | 
  •  

Domanda

I'm want to fill hdr (struct) variable with data from in.wav file and I want to copy the first 64 bytes of in.wav file to another file (out.wav).

But! When using fread() the second time it starst to copy in.wav from the place where it finished when using fread() the first time. Why?

#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;
}

What is the matter?

È stato utile?

Soluzione

This is intended. fread always reads from the file's current read pointer and advances that same pointer, so you can a file in sequential chunks without having to explicitly seek.

You shouldn't have to read the same chunk twice in a row. What you're checking this way is whether some other process has changed the file in the meantime, and if one has, then your program will erroneously report that the copy failed.

Altri suggerimenti

The file pointer is moved. Read more about it here: Does fread move the file pointer? . You can use fseek or rewind to position at the beginning of a file.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top