5

Why use fread () the 2nd time, it reads a file from the beginning but from the e...

 2 years ago
source link: https://www.codesd.com/item/why-use-fread-the-2nd-time-it-reads-a-file-from-the-beginning-but-from-the-end-of-the-reading-by-1-fread.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Why use fread () the 2nd time, it reads a file from the beginning but from the end of the reading by 1-fread ()?

advertisements

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?


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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK