murzagurskiy
murzagurskiy

Reputation: 1323

Unclear reading file in C

I tried cyclically read file in buffer of 100 byte. When i read file first time - buffer was full. Returned value is 0. No error and no eof (functions "ferror" and "feof" shows no error). Then i tried read file second time and again returned value is 0, no error and no eof. But then i have empty buffer. I don't know what is the problem?

if(fopen_s(&file_in, argv[1], "rb") == 0){ 
    printf("File was opened.\n");

    while(!feof(file_in)){ 
        read_code = fread_s(file_data, 100, sizeof(unsigned char), 100, file_in); 
        if(ferror(file_in)) {
            printf("Error!\n");
        }
        if(feof(file_in)) {
            printf("Eof!\n");
        }
        printf("Read result: %d\n", read_code);
        /*Using the buffer*/
        memset(file_data, 0, 100);
    }
    fclose(file_in);
}

Upvotes: 0

Views: 155

Answers (1)

ryyker
ryyker

Reputation: 23208

For the reasons given in comments regarding fopen_s, et. al., Here is an alternative implementation of reading a binary file using getc(), along with fopen(), fclose(), etc. (I am not using a Microsoft implementation, but am using ANSI C99)

It has a commented section I used to create a test binary file. Other than that it sizes the file you are reading so you can allocate the right amount of memory, then reads the binary data into a buffer.

For navigating your file, take a look at fseek() with its stdio.h defined arguments:

#define SEEK_SET     0
#define SEEK_CUR     1
#define SEEK_END     2

In this example, everything is closed or freed before exiting:

#include <windows.h>
#include <ansi_c.h>

long int getFileSizeFromPath(char * path)
{
    FILE * file;
    long int fileSizeBytes = 0;
    file = fopen(path,"r");
    if(file){
        fseek(file, 0, SEEK_END);
        fileSizeBytes = ftell(file);
        fseek(file, 0, SEEK_SET);
        fclose(file);
    }
    return fileSizeBytes;
}

int main(int argc, char *argv[])
{
    FILE *fp=0;
    char *binBuf;
    long int size=0;
    int i=0;
    int byte=0;

//create 100 byte test file (c:\\dev\\tessst.bin)   
//  fp = fopen(argv[1], "wb");
//
//  srand(clock()); 
//  for(i=0;i<100;i++)
//  {
//      byte = rand();
//      putc(byte, fp); 
//  }
//  putc(EOF, fp);
//  
//  fclose(fp);

    size = getFileSizeFromPath(argv[1]);
    binBuf = calloc(size + 1, sizeof(char));

    fp = fopen(argv[1], "rb");
    byte = getc(fp);
    while(byte != EOF)
    {
        binBuf[i++] = (char)byte;
        byte = getc(fp);
    }
    fclose(fp);
    free(binBuf);

    return 0;
}

Upvotes: 1

Related Questions