Re: im facing problem with fread()??
- From: "Nick Keighley" <nick_keighley_nospam@xxxxxxxxxxx>
- Date: 24 Aug 2005 04:01:29 -0700
Rajshekhar wrote:
> i am writing a simple prgm to read a .txt file
if it's a text file use fgets() rather than fread()
> then store the contents
> into the array...
> program as follows:
> --------------------------
> #include<stdio.h>
#include <stdio.h>
> int main()
int main (void)
> {
> FILE *fp1;
> int buf[5];
> int num,i;
>
> fp1=fopen("triangle.txt","r");
> if(fp1 == NULL)
> {
> printf("file cant be opend");
> exit(0);
> }
>
> num=fread(buf,sizeof(int),5,fp1);
> printf("num of elements read =%d\n",num);
>
> for(i=0;i<5;i++)
> printf("%d\n",buf[i]);
here we have a fundamental misconception. Lets suppose your file looks
like this:
3 4 5
I'm guessing your program wants to read three numbers (because it's
called triangle.txt). If you read raw binary and your file is in ASCII
you'll actually read the following bytes:
51 32 52 32 53
So you need to convert these bytes into numbers (or use %c istead of %d
in the above printf()). Try this:-
if (scanf (buf "%d %d %d", &j, &k, &m) != 3)
{
printf ("can't parse line\n");
exit (1);
}
else
printf ("read %d, %d %d\n", j, k, m);
declare j, k and m as int
> return 0;
> }
>
> ------------------
> i am getting no.of elements read as 0,but file is openable...
> the elements as junk numbers...
hmm. I only just noticed this. I don't know what your file looks like.
I don't know what "junk number" are. You've told it read five lots of
4 bytes (assuming 32-bit ints). Probably not what you meant. That won't
fit in a 5 bytes array. Really do change over to fgets(). fread() is
for binary data. fread() may not handle end of line and end of file
correctly.
> can anybody tell me wat is the problem in doing this ..????
> is it that i m using fread wrongly or it behaves abnoramlly???
I suggest you get a good book. Eg. K&R.
--
Nick Keighley
Quantum Boggum Sort:
Q1. use a source of quantum noise (eg. radioactive decay) to
randomly permutate an array.
Q2. if the array is not ordered, destroy the universe (*)
Q3. if you reached this step your universe has sorted the array
in O(n) time.
(*) [100] this is left as a exercise
.
- References:
- im facing problem with fread()??
- From: Rajshekhar
- im facing problem with fread()??
- Prev by Date: Re: im facing problem with fread()??
- Next by Date: Re: function (const char *) vs. function (char *)
- Previous by thread: Re: im facing problem with fread()??
- Next by thread: Re: im facing problem with fread()??
- Index(es):
Relevant Pages
|