How to read int number from binary file in C

2 Answers

0 votes
#include <stdio.h>

int main(void)
{
    int n;
    FILE *fp;

    fp = fopen("d:\\data.bin","rb");
    if (!fp)
    {
        printf("Unable to open file");
        return 1;
    }
    while( 1 )
    {
        fread(&n, sizeof(int), 1, fp);
        if(feof(fp)) break;
        printf("%d\n", n);
    }
    
    fclose(fp);
 
    return 0;
}

/*
run: (the content of d:\\date.bin)

100
200
300

*/


answered Oct 18, 2014 by avibootz
0 votes
#include <stdio.h>
 
int main(void)
{
    int n;
    FILE *fp;

    fp = fopen("d:\\data.bin","rb");
    if (!fp)
    {
        printf("Unable to open file");
        return 1;
    }
    while( fread(&n, sizeof(int), 1, fp) == 1 )
    {
        printf("%d\n", n);
    }
    
    fclose(fp);
 
    return 0;
}

/*
run: (the content of d:\\date.bin)

100
200
300

*/


answered Oct 18, 2014 by avibootz

Related questions

1 answer 370 views
1 answer 160 views
1 answer 125 views
1 answer 141 views
...