im facing problem with fread()??

R

Rajshekhar

Hi ,
i am writing a simple prgm to read a .txt file then store the contents
into the array...
program as follows:
--------------------------
#include<stdio.h>

int main()
{
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);
return 0;
}

------------------
i am getting no.of elements read as 0,but file is openable...
the elements as junk numbers...

can anybody tell me wat is the problem in doing this ..????
is it that i m using fread wrongly or it behaves abnoramlly???

TIA
Regards,
Rajshekhar
 
K

Kuku

The file triangle.txt must be empty that's why it is returning 0 number
of elements and junk value there on
 
R

Rajshekhar

no its not empty ....!!
i read the contents of it using,,,,,getc & printed them using putc

~Rajshekhar
 
M

manoj1978

Rajshekhar said:
Hi ,
i am writing a simple prgm to read a .txt file then store the contents
into the array...
Please post the contents of triangle.txt.then someone can help you.
If triangle.txt is a binary file then try rb instead of r in fopen.
program as follows:
--------------------------
#include<stdio.h>

int main()
{
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);
return 0;
}

------------------
i am getting no.of elements read as 0,but file is openable...
the elements as junk numbers...

can anybody tell me wat is the problem in doing this ..????
is it that i m using fread wrongly or it behaves abnoramlly???

TIA
Regards,
Rajshekhar
 
R

Rajshekhar

hi
the file triangle.txt contents are...
6 6 4

thats it .....
i dont think this file is binary file ..!!!
 
V

Villy Kruse

Please post the contents of triangle.txt.then someone can help you.
If triangle.txt is a binary file then try rb instead of r in fopen.

The way fread() in program is used strongly suggests that the file has
to be binary. A text file is better read using fscanf(), or a combination
of fgets() and sscanf(), or som variant of getc()/getchar().

Villy
 
V

Villy Kruse

hi
the file triangle.txt contents are...
6 6 4

thats it .....
i dont think this file is binary file ..!!!


If sizeof(int) on your system is greater than the total number of bytes
in the input file there are not enough data for even the first element,
and thus you read zero elements.

Villy
 
C

Cong Wang

Rajshekhar said:
hi
the file triangle.txt contents are...
6 6 4

thats it .....
i dont think this file is binary file ..!!!
No,you are wrong!That depends on how you treat it!If you want to open
is as a binary file,it is a binary file!Text files are similar.
 
N

Nick Keighley

Rajshekhar said:
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:

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);


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;
}

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
 
C

Christopher Benson-Manica

Rajshekhar said:
#include<stdio.h>

The prototype for exit() is in stdlib.h, which you forgot to include.
int main()
{
FILE *fp1;
int buf[5];
int num,i;
fp1=fopen("triangle.txt","r");

num=fread(buf,sizeof(int),5,fp1);

Consider what you are doing here. You are asking for the first sizeof
int * 5 bytes of the file (probably 20); if the file contains 6 4 4,
buf[0] will contain four bytes that correspond to the internal
representations of '6', ' ', and '4'. As already noted, you'd be much
better off reading the contents of this file using fgets() and using
strtol() and friends to get your integers.
printf("num of elements read =%d\n",num);
for(i=0;i<5;i++)

As a side note, if you know you read num bytes from the file, why not
iterate num times through buf?
printf("%d\n",buf);
return 0;
}
 
L

l4learn

Hello ...
In the above code the file is not closed ....use something like
fcloseall() at the least to at the end of the programs where u use
files ..

the problem with ur program is here

#include<stdio.h>




----> num=fread(buf,sizeof(int),5,fp­1); /*this takes in values in
ascii format .. and stores the ascii values ...
printf("num of elements read =%d\n",num);


for(i=0;i<5;i++)
printf("%d\n",buf); /* here use %c to print the numbers .. it
will convert the ascii to their corresponding chars ... that is the
numbers u want .. */
return 0;
/*fcloseall() or fclose(fp1); here please


}


i didnot wish to offend any one by this mail.....
 
P

P.J. Plauger

In the above code the file is not closed ....use something like
fcloseall() at the least to at the end of the programs where u use
files ..

the problem with ur program is here

#include<stdio.h>

A conforming C implementation closes all files at program shutdown.
It also does *not* contain a call to fcloseall, which is not part
of the C Standard.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
 
J

Jason Curl

Rajshekhar said:
hi
the file triangle.txt contents are...
6 6 4

thats it .....
i dont think this file is binary file ..!!!

Rajshekhar, please quote what you're replying to in your message. I for
one can't always see what it is you're replying to, so sometimes your
reply looks like gibberish without context. You'll see this mentioned
often in the newsgroup if you've been reading for some time. It makes it
much more difficult for people to answer you (and decreases the
likelihood that they do)

Looking at the prototype for fread, it is:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

Based on your program, it tries to read 5*(sizeof int) from the file.
That's because it doesn't care about spaces, commas or other
punctuation. For that you should look at some other functions such as
fscanf, or write your own parser (much more recommended). There have
been numerous posts to this newsgroup asking the same question you have
in the last month - so please go have a look.

I don't know what the size of an int is on your machine, but it's
probably 4 or 8.

From the description I have of 'fread', it says:
"The function fread reads nmemb elements of data, each size bytes
long, from the stream pointed to by stream, storing them at the location
given by ptr."

This means, if your file has the contents:

6 6 4

This looks like (in binary)

0x36 0x20 0x36 0x20 0x34 (values are in hex)

So, I expect the first value to be something like 0x36203620 or
0x20362036 depending on the endianness of your machine (one big hex
number, that probably looks random).

The fact that you're getting a result of zero from fread() might be
because sizeof int is 8 bytes (there aren't 8 bytes in your file
triangle.txt).

Indeed, when I compile your program, I get the result:
num of elements read =1
540418102
134482484
-1075253336
134513429
0

Now ignoring the last 4 digits (because num=1), converting 540418102 to
hex we have exactly 0x20362036 (I'm running an Intel, little endian - a
Mot 68k would give a different result). This is exactly what I had expected.

Also, you have other problems in your code. I'll post it here again:

#include<stdio.h>

/* ** You should include other headers here as well, such as */
#include <stdlib.h>
/* as otherwise exit() is not defined */

/* ** You should use int main(void), in C the empty brackets is
discouraged and is the old style. Also the meaning between C and C++ is
different so portability is lost */
int main()
{
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);

/* Instead of 'i<5' you should use 'i<num'. That way your not going to
access elements of buf[] that aren't initialised. This is why the last 4
values in my output (sizeof int == 4) are also garbage */
for(i=0;i<5;i++)
printf("%d\n",buf);
return 0;
}
 
E

Emmanuel Delahaye

Rajshekhar wrote on 24/08/05 :
hi
the file triangle.txt contents are...
6 6 4

Ok, a text file.
thats it .....
i dont think this file is binary file ..!!!

fopen() the file in text mode ("r")

You want fgets() to get the line and sscanf() with "%d %d %d" to parse
it.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++
 
S

Suman

Jason said:
Rajshekhar said:
hi
the file triangle.txt contents are...
6 6 4

thats it .....
i dont think this file is binary file ..!!!

Rajshekhar, please quote what you're replying to in your message. I for
one can't always see what it is you're replying to, so sometimes your
reply looks like gibberish without context. You'll see this mentioned
often in the newsgroup if you've been reading for some time. It makes it
much more difficult for people to answer you (and decreases the
likelihood that they do)

Looking at the prototype for fread, it is:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

Based on your program, it tries to read 5*(sizeof int) from the file.
That's because it doesn't care about spaces, commas or other
punctuation. For that you should look at some other functions such as
fscanf, or write your own parser (much more recommended). There have
been numerous posts to this newsgroup asking the same question you have
in the last month - so please go have a look.

I don't know what the size of an int is on your machine, but it's
probably 4 or 8.

From the description I have of 'fread', it says:
"The function fread reads nmemb elements of data, each size bytes
long, from the stream pointed to by stream, storing them at the location
given by ptr."

This means, if your file has the contents:

6 6 4

This looks like (in binary)

0x36 0x20 0x36 0x20 0x34 (values are in hex)

So, I expect the first value to be something like 0x36203620 or
0x20362036 depending on the endianness of your machine (one big hex
number, that probably looks random).

The fact that you're getting a result of zero from fread() might be
because sizeof int is 8 bytes (there aren't 8 bytes in your file
triangle.txt).

Indeed, when I compile your program, I get the result:
num of elements read =1
540418102
134482484
-1075253336
134513429
0

Now ignoring the last 4 digits (because num=1), converting 540418102 to
hex we have exactly 0x20362036 (I'm running an Intel, little endian - a
Mot 68k would give a different result). This is exactly what I had expected.

Also, you have other problems in your code. I'll post it here again:

#include<stdio.h>

/* ** You should include other headers here as well, such as */
#include <stdlib.h>
/* as otherwise exit() is not defined */

/* ** You should use int main(void), in C the empty brackets is
discouraged and is the old style. Also the meaning between C and C++ is
different so portability is lost */
int main()
{
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);

/* Instead of 'i<5' you should use 'i<num'. That way your not going to
access elements of buf[] that aren't initialised. This is why the last 4
values in my output (sizeof int == 4) are also garbage */
for(i=0;i<5;i++)
printf("%d\n",buf);


... to say nothing of the missing fclose()!
 
J

Jason Curl

Suman said:
Jason said:
Rajshekhar said:
hi
the file triangle.txt contents are...
6 6 4

thats it .....
i dont think this file is binary file ..!!!

Rajshekhar, please quote what you're replying to in your message. I for
one can't always see what it is you're replying to, so sometimes your
reply looks like gibberish without context. You'll see this mentioned
often in the newsgroup if you've been reading for some time. It makes it
much more difficult for people to answer you (and decreases the
likelihood that they do)

Looking at the prototype for fread, it is:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

Based on your program, it tries to read 5*(sizeof int) from the file.
That's because it doesn't care about spaces, commas or other
punctuation. For that you should look at some other functions such as
fscanf, or write your own parser (much more recommended). There have
been numerous posts to this newsgroup asking the same question you have
in the last month - so please go have a look.

I don't know what the size of an int is on your machine, but it's
probably 4 or 8.

From the description I have of 'fread', it says:
"The function fread reads nmemb elements of data, each size bytes
long, from the stream pointed to by stream, storing them at the location
given by ptr."

This means, if your file has the contents:

6 6 4

This looks like (in binary)

0x36 0x20 0x36 0x20 0x34 (values are in hex)

So, I expect the first value to be something like 0x36203620 or
0x20362036 depending on the endianness of your machine (one big hex
number, that probably looks random).

The fact that you're getting a result of zero from fread() might be
because sizeof int is 8 bytes (there aren't 8 bytes in your file
triangle.txt).

Indeed, when I compile your program, I get the result:
num of elements read =1
540418102
134482484
-1075253336
134513429
0

Now ignoring the last 4 digits (because num=1), converting 540418102 to
hex we have exactly 0x20362036 (I'm running an Intel, little endian - a
Mot 68k would give a different result). This is exactly what I had expected.

Also, you have other problems in your code. I'll post it here again:

#include<stdio.h>

/* ** You should include other headers here as well, such as */
#include <stdlib.h>
/* as otherwise exit() is not defined */

/* ** You should use int main(void), in C the empty brackets is
discouraged and is the old style. Also the meaning between C and C++ is
different so portability is lost */
int main()
{
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);

/* Instead of 'i<5' you should use 'i<num'. That way your not going to
access elements of buf[] that aren't initialised. This is why the last 4
values in my output (sizeof int == 4) are also garbage */
for(i=0;i<5;i++)
printf("%d\n",buf);



... to say nothing of the missing fclose()!


Most modern operating systems take care of this usually, but it is good
to not assume anything about the OS.
 
C

Christopher Benson-Manica

Suman said:
(snip gratuitous quoted text)
... to say nothing of the missing fclose()!

1) You might trim your attributions judiciously when making short posts.
2) The eminent Mr. Plauger stated elsethread that a conforming
implementation closes all open files when the program ends.
 
P

Peter Shaggy Haywood

Groovy hepcat Rajshekhar was jivin' on 24 Aug 2005 02:29:14 -0700 in
comp.lang.c.
im facing problem with fread()??'s a cool scene! Dig it!
i am writing a simple prgm to read a .txt file then store the contents
into the array...
program as follows:
--------------------------
#include<stdio.h>

int main()
{
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);
return 0;
}


You are apparently trying to read binary data from a file with a
.txt extention (suggesting it's a text file) opened in text mode. That
can't possibly be right. Does the file actually contain text data? If
so, read it with a text reading function such as fscanf(). If it is
actually binary, however, give your file a different extention (to
prevent anyone using it being confused as to its true contents) and
open it in binary mode.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
 
S

Suman

Christopher said:
1) You might trim your attributions judiciously when making short posts.

Oh, sure I will.
2) The eminent Mr. Plauger stated elsethread that a conforming
implementation closes all open files when the program ends.

It does so indeed. However, I don't consider it a good practice to
leave things to the system when you ought to[1] do it yourself.
I have had seen code that crashed, because it was only opening
files, and thousands of them, at a time, and not closing them.
My point is -- it is better to be complete, always.
Even for short programs, where it hardly matters. To make it a
matter of habbit. It might not matter for *that* particular problem,
but later, when you least want it to -- it might just.

[1] ought to -- a very subjective one
 
K

Keith Thompson

Suman said:
Christopher said:
1) You might trim your attributions judiciously when making short posts.

Oh, sure I will.
2) The eminent Mr. Plauger stated elsethread that a conforming
implementation closes all open files when the program ends.

It does so indeed. However, I don't consider it a good practice to
leave things to the system when you ought to[1] do it yourself.
I have had seen code that crashed, because it was only opening
files, and thousands of them, at a time, and not closing them.
My point is -- it is better to be complete, always.
Even for short programs, where it hardly matters. To make it a
matter of habbit. It might not matter for *that* particular problem,
but later, when you least want it to -- it might just.

Sure, you should always fclose() any file that you fopen() -- not
because you can't count on the implementation to do it for you, but
because it's good style. Any implementation that doesn't properly
close all open files when the program terminates is broken, but if I
write my own code properly I'll never notice.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top