arsy
arsy

Reputation: 25

reading binary file in c until the end of file

I have a binary file with some lines into it(I don't know how much exactly) and I want to read this lines into struct until the end of file and then rewrite this lines in new file.txt. My question is: How can I read from binary file into struct until the end of file? It prints only first 11 lines. Must I allocate memory for this or smth?

    struct linien
    {
        short x1, x2, y1, y2;
        unsigned char R, G, B;
    };


    FILE *fp; // pointer to a file type
    FILE *fpa; // pointer to a file type

    int counter;
    struct linien x; //x is a variable of type struct linien

    //open files - one for reading and another one for writing
    fp = fopen("\\Linien.pra", "rb");
    fpa = fopen("\\Linien.txt", "w");

    //check to see if files opened succesfully 
    if ((fp == NULL)||(fpa == NULL))
    {
        printf("file failed to open\n");
    }

the for loop doesn't seem to work correctly.

    else
    {
        for (counter = 0; counter < sizeof(x); counter++) //print and write lines
        {
            //read the file Linien.pra
            fread(&x, sizeof(x), 1, fp);
            printf("%2d\t %3d\t %4d\t %5d\t %6d\t %7d  %8d\n", x.x1, x.x2, x.y1, x.y2, x.R, x.G, x.B);  
            //write struct linien to new file Linien.txt
            fprintf(fpa, "%2d\t %3d\t %4d\t %5d\t %6d\t %7d  %8d\n", x.x1, x.x2, x.y1, x.y2, x.R, x.G, x.B);
        }

        fclose(fp); // close file
        fclose(fpa); // close file
    }

Upvotes: 0

Views: 5112

Answers (3)

user2371524
user2371524

Reputation:

It prints only first 11 lines

Let's see ....

struct linien
{
    short x1, x2, y1, y2;
    unsigned char R, G, B;
};

int counter;
struct linien x;

// [...]

for (counter = 0; counter < sizeof(x); counter++)
{
    // code to read **one** instance of `struct linien`
}

See something? What's sizeof(x)? We have 4 short and 3 char in struct linien -- assuming your typical platform where short has a size (and alignment requirement) of 2, this makes a total of 2*4 + 3 = 11. Suprise? ;)

You're looping exactly 11 times, for what reason ever. So you read (and write) 11 items!

Instead, you should only stop once your fread() call fails (test the return value!).

Upvotes: 0

HrishiB
HrishiB

Reputation: 61

Make sure the structs in file match with the struct linien. Check for the return value of fread , to check if you reached the end of the file.

Upvotes: 0

user1801517
user1801517

Reputation:

You should check the return value of fread so you can use fread in a while loop like that:

while (fread(&x, sizeof(x), 1, fp) != 0)
{
}

Upvotes: 1

Related Questions