saravanakkumar
saravanakkumar

Reputation: 21

reading files in binary mode

i am new to reading data from files.i tried to get the data from a text file and print them using the below code.but instead all i get is junk values.it has to type the following data

12 13 14

The code

void main()
{
    FILE *fp;
    int a=0;
    fp=fopen("try.txt","rb");
    fseek(fp,0,SEEK_END);
    long int size=ftell(fp);
    fseek(fp,0,SEEK_SET);
    for(int i=0;i<size;i++)
    {
        fread(&a,sizeof(int),1,fp);
        printf("%d\t",a);
    }
    fclose(fp);
    getch();
}

but instead what i'm getting is the following values

822686257  875628851  875628851  875628851  875628851
875628851  875628851  875628851

i read other answers given related to fread but i still couldnt understand the problem.i'm using visual c++ 2010 express

Upvotes: 1

Views: 14041

Answers (2)

Sourav Tiwari
Sourav Tiwari

Reputation: 39

Don't take it as binary. Try this code instead:

int no;
std::ifstream fin("try.txt", std::ios::in|std::ios::beg);
if(!fin)
{
    std::cout<<"Cannot open for reading\n";
    return;
}
while(fin>>no)
{
    std::cout<<no<<std::endl;
}

Upvotes: 0

AndersK
AndersK

Reputation: 36082

int main() // note: int
{
 FILE *fp;
 int a=0;
 fp=fopen("try.txt","rb");
 fseek(fp,0,SEEK_END);
 long int size=ftell(fp); // now you got size of file in bytes
 fseek(fp,0,SEEK_SET);    // same as rewind(fp)
 for(int i=0;i<size;i++)
 {
    fread(&a,sizeof(int),1,fp); // you read one int (sizeof(int)!=1 byte)
    printf("%d\t",a);
  }
  fclose(fp);
  getch();
  return 0; // since int main()
}

instead, if you want to read ints from the file you must change the number of elements you read

for (int i = 0; i < size/sizeof(int); ++i)
{
...
}

EDIT:

When looking a bit more carefully on your values in hex a pattern can be seen

31093231

31 is hex for 1, 09 is hex for tab and so on, fread expects the values in the file to be in binary format, at least as you wrote it above so that 12 would be stored as 0x0001 (or whatever your endianess and size of int is) but what can be seen is the ASCII value of the value so you shouldn't use fread() instead use fgetc() instead:

int main() 
{
 FILE *fp;
 int a=0;
 fp=fopen("try.txt","rb");
 if ( fp != NULL )
 {
   do
   {
     a = fgetc(pFile); // read one character
     if ( a != EOF ) putchar( a );
   }
   while ( a != EOF );
 }

 fclose(fp);
 getch();
 return 0; 
}

Upvotes: 3

Related Questions