Re: question on fread()
From: Joona I Palaste (palaste_at_cc.helsinki.fi)
Date: 02/17/04
- Next message: Mark McIntyre: "Re: Mystery: static variables & performance"
- Previous message: ben: "Re: how to simplify/shorten this loop of bit shifting code?"
- In reply to: syntax: "question on fread()"
- Next in thread: syntax: "Re: question on fread()"
- Reply: syntax: "Re: question on fread()"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 17 Feb 2004 19:01:48 GMT
syntax <sanko50@yahoo.com.hk> scribbled the following:
> hi here is my test code
> include<stdio.h>
> #include<stdlib.h>
> int main()
> {
> FILE *ptr1 = fopen("c:\\test1.txt","rb");
> if(!ptr1) printf("not openedl");
> int b[50];
> fread(b,9,4,ptr1);
> for(int k=0;k<6;k++)
> printf("%d\n",b[k]);
> }
> test1.txt
> ----------
> 1 2 3 4 5
> 6 7 8 9 0
> output
> -------
> 540155953
> 540287027
> 906628405
> 941635360
> 807418144
> -390643
> my question > how this output is coming ? why not the output is 1 2 3
> 4 5
> 6 ?
> i am not asking how can i do it .....but i am asking the explanation
> why and how that garbage output is coming ? is that a garbage at all?
> or have some maths behind that?
Your code is reading the bytes in the file into integers (which I
think are 4 bytes on your computer) and then printing the decimal
value of those integers. This decimal value is not the same as the
characters those bytes represent in your character set. You'll
probably want to look up fgets() instead of fread() and use "%s" for
printing instead of "%d".
> is it true that i can not use fread() to read text file? if not can u
> show a code which uses fread() like above but outputing 1 2 3 4 5 6
> instead of garbage ?
Of course you can use fread() to read text files. But you have to be
careful what you make it read. It's usually best to make the element
size 1 byte - any higher and the phenomenon I described above will
occur. Also note that you really must use "%s" or "%c" in printf()
rather than "%d", because "%d" is for printing the byte's decimal
value, not the character it represents.
I could write a full program to do what I am trying to describe but I
am too tired. Some C guru can write it for us.
-- /-- Joona Palaste (palaste@cc.helsinki.fi) ------------- Finland --------\ \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/ "Make money fast! Don't feed it!" - Anon
- Next message: Mark McIntyre: "Re: Mystery: static variables & performance"
- Previous message: ben: "Re: how to simplify/shorten this loop of bit shifting code?"
- In reply to: syntax: "question on fread()"
- Next in thread: syntax: "Re: question on fread()"
- Reply: syntax: "Re: question on fread()"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|