473,387 Members | 1,904 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

why is fread forgetting where its position?

I found this very odd and maybe someone can explain it to me.

I was using fread to scan through a binary file and pull bytes out. In
the middle of a while loop, for no reason that i could discern, fread
all the sudden kept returning the same byte over and over as if it were
no longer advancing in the file. I used a hex editor to determine the
address of the last byte read in the file. CF was the last address, D0
was not ever read although my while loop kept running.

when i tried to use ftell to try to debug the problem, the program ran
fine. mmm, so i took the ftell out and the program ceased working
again. the ftell wasn't doing anything that i could tell. this is my
loop:

while (blah2!=3220) // I'm still working out bugs and using
temporary variables like "blah"
{
fread(&newval,BPS,1,WavInPtr); //put new byte in
newval

blah=oldval^newval[0];

ftell(WavInPtr); // fread forgets about itself
without this
if(blah < 0)
{
oldval = newval[0];
fprintf(WavOutPtr,"%ld \n",period_cntr);
period_cntr=0;

}

++period_cntr;

++blah2;
}

as you can see, ftell isn't attached to anything, it isn't doing
anything that i can see. but if i take it out, the program just runs
fine to a certain point and then stops making sense.

I'm compiling on Dev-c++ 4.9.9.2

I'd be glad to send the source code to anyone who wants to play with it
themselves. it requires a small wav file that comes with it.

Sep 29 '06 #1
13 3510
There are these things called "return values" from library routines.
It's often a good idea to see what they say, like at each and every
function call.

I suspect fread is detecting end of file. Quite possible, if it did
hit end of file, or if you opened up the file in "text" mode.

Sep 29 '06 #2
Ancient_Hacker wrote:
There are these things called "return values" from library routines.
It's often a good idea to see what they say, like at each and every
function call.
thanks much for the sarcasm. Actually, what i posted was the last step
in the debugging process, the bare minimum to get the program to
function. previously i had been printing the result of ftell after
each loop. I saw it incrementing, but i also saw the program function
properly. without this call to ftell (and without it only), the
program does not procede past a certain point in the file. it repeats
the same byte from the middle of the file (or, possibly, returns no
value at all, didn't test for that, oops).
I suspect fread is detecting end of file. Quite possible, if it did
hit end of file, or if you opened up the file in "text" mode.
Ah, i did open the file in text mode. Thank you for pointing that out.
This probably does affect things, however, it doesn't explain how a
call ftell allows the program to read all the way through the file. If
i had hit a data point that had the same bit pattern as an eof (which
it didn't, it hit decimal 31), would it continuoulsy return the same
byte or have no return value at all? or would it scroll off through
memory, reading the next consecutive bits?

Any insight into this quirk would be interesting to hear, thanks.

Sep 29 '06 #3
>There are these things called "return values" from library routines.
>It's often a good idea to see what they say, like at each and every
function call.

thanks much for the sarcasm. Actually, what i posted was the last step
in the debugging process, the bare minimum to get the program to
function. previously i had been printing the result of ftell after
each loop.
Did you also print the result of fread() after you called it?
>I saw it incrementing, but i also saw the program function
properly. without this call to ftell (and without it only), the
program does not procede past a certain point in the file. it repeats
the same byte from the middle of the file (or, possibly, returns no
value at all, didn't test for that, oops).
If fread() returns 0 or -1, DON'T EVEN LOOK at the value in the buffer.
>I suspect fread is detecting end of file. Quite possible, if it did
hit end of file, or if you opened up the file in "text" mode.

Ah, i did open the file in text mode. Thank you for pointing that out.
This probably does affect things, however, it doesn't explain how a
call ftell allows the program to read all the way through the file. If
i had hit a data point that had the same bit pattern as an eof (which
it didn't, it hit decimal 31), would it continuoulsy return the same
byte or have no return value at all? or would it scroll off through
memory, reading the next consecutive bits?
fread() returns an integer value. It cannot return "no return value at all".

Sep 30 '06 #4
hey gordon,
Did you also print the result of fread() after you called it?
If fread() returns 0 or -1, DON'T EVEN LOOK at the value in the buffer.
yes, i did. or rather, i put fread into a variable and then printed
that valiable. I kept geting 31.
fread() returns an integer value. It cannot return "no return value at all".
I was pretty sure that this was the case. but since my integer that
fread was retuned into kept giving the same response, the two
possiblities were 1) fread keeps giving the same byte or 2) fread isnt
writing into the memory space of that variable.

The real question is still how does a call to ftell affect the way
fread works, either by affecting the file pointer, or some buffer or
something. atleast, thats what seems to me to be happening, because
adding and subtracting that one call to ftell drastically changes the
output of my program, and the input is not changing at all.

thanks

Oct 1 '06 #5
010 010 wrote:
The real question is still how does a call to ftell affect the way
fread works, either by affecting the file pointer, or some buffer or
something. atleast, thats what seems to me to be happening, because
adding and subtracting that one call to ftell drastically changes the
output of my program, and the input is not changing at all.
You're seeing undefined behavior. Most likely because you did something to
create a situation that invokes undefined behavior. ftell() does not affect
fread().

Just give us the whole function source that we can work with or pull things up
in a debugger of some sort - because this is shooting in the dark at this
point unfortunately.
Oct 1 '06 #6
I still havent seen any unequivocal statement that you're printing out
the value that fread returns as it's function value. NOT the data
value that it's supposed to return in the first parameter's address.
You shouldnt look at that until you've verified that indeed fread says
it returned something, as indicated by the value it returns.

For extra info, clear out the buffer before the fread, like, put a '?'
into it. I suspect fread will do nothing in that last case and you'll
see a '?' still sitting in the buffer.

Oct 1 '06 #7
>Did you also print the result of fread() after you called it?
>If fread() returns 0 or -1, DON'T EVEN LOOK at the value in the buffer.

yes, i did. or rather, i put fread into a variable and then printed
that valiable. I kept geting 31.
ret = fread(&newbuf, 1, 1, f);

In the above statement, the return value of fread() has everything to do
with the value of ret and nothing whatever to do with what's in newbuf.
You should not look at any values in newbuf until you have verified that
ret 0.

If your code contains a statement like:

fread(&newbuf, 1, 1, f);

you obviously didn't use the return value of fread(). Replace this statement
with:
remove(__FILE__);

Some bad code should be shot on sight.
Oct 1 '06 #8

010 010 wrote:
hey gordon,
Did you also print the result of fread() after you called it?
If fread() returns 0 or -1, DON'T EVEN LOOK at the value in the buffer.

yes, i did. or rather, i put fread into a variable and then printed
that valiable. I kept geting 31.
fread() returns an integer value. It cannot return "no return value at all".

I was pretty sure that this was the case. but since my integer that
fread was retuned into kept giving the same response, the two
possiblities were 1) fread keeps giving the same byte or 2) fread isnt
writing into the memory space of that variable.

The real question is still how does a call to ftell affect the way
fread works, either by affecting the file pointer, or some buffer or
something. atleast, thats what seems to me to be happening, because
adding and subtracting that one call to ftell drastically changes the
output of my program, and the input is not changing at all.

thanks
At a guess. You are stomping on memory somewhere before the fread
loop.
This memory stomp causes fread to fail. You do not check the
return value of fread and do not know it has failed. When fread fails
it does nothing to the input buffer, so the value that you are looking
at does not change (To check this try resetting newval between calls
to fread). The ftell call either sets the stomped on memory to
something less harmfull, or changes the memory layout in such
a way that the place that gets stomped is different (have you tried
using some other function than ftell, or changing optimization levels?)
The problem probably has little to do with fread or ftell. Try to
find
the memory stomp (do you have any memory debugging tools?)

-William Hughes

Oct 2 '06 #9
Groovy hepcat 010 010 was jivin' on 29 Sep 2006 13:05:47 -0700 in
comp.lang.c.
why is fread forgetting where its position?'s a cool scene! Dig it!
>I found this very odd and maybe someone can explain it to me.

I was using fread to scan through a binary file and pull bytes out. In
the middle of a while loop, for no reason that i could discern, fread
all the sudden kept returning the same byte over and over as if it were
no longer advancing in the file. I used a hex editor to determine the
address of the last byte read in the file. CF was the last address, D0
was not ever read although my while loop kept running.

when i tried to use ftell to try to debug the problem, the program ran
fine. mmm, so i took the ftell out and the program ceased working
again. the ftell wasn't doing anything that i could tell. this is my
loop:

while (blah2!=3220) // I'm still working out bugs and using
temporary variables like "blah"
{
fread(&newval,BPS,1,WavInPtr); //put new byte in
newval

blah=oldval^newval[0];

ftell(WavInPtr); // fread forgets about itself
without this
if(blah < 0)
{
oldval = newval[0];
fprintf(WavOutPtr,"%ld \n",period_cntr);
period_cntr=0;

}

++period_cntr;

++blah2;
}
Ye gads! Show us something that will compile. Make it legible.
Indent consistently, and not too far at each level. Two to four spaces
per indentation level should be fine. Don't use // comments here. They
have a nasty tendancy to wrap, making it harder for us to copy, paste
and compile your code. Use /* */ comments only, when posting here.
Show us the smallest *complete* program that demonstrates the
problem. By "complete" I mean something you expect to compile and run.
Cut out everything extraneous, anything that does not demonstrate the
problem. (And do try to compile the cut-down version of your code.)
Explain precisely but concisely what you expect the code to do, as
well as what it actually does.
Show us the data you're attempting to work on. If it's non-textual
data, attempt to provide some textual interpretation of this (eg., a
hex dump). Of course, if your dataset is large, you may need to
truncate it.
Without being provided all this information, all we can do is guess
what might be wrong. Remember, you want our help; so you're going to
have to do the work. Help us to help you. You're not likely to get
much help if you just say, effcetively, "Here's an uncompilable,
incomplete and barely legible snippet of code. Why doesn't it work?".
>as you can see, ftell isn't attached to anything, it isn't doing
anything that i can see. but if i take it out, the program just runs
fine to a certain point and then stops making sense.

I'm compiling on Dev-c++ 4.9.9.2

I'd be glad to send the source code to anyone who wants to play with it
themselves. it requires a small wav file that comes with it.
Let me guess. You've opened the file in text 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"?
Oct 2 '06 #10
>Did you also print the result of fread() after you called it?
>If fread() returns 0 or -1, DON'T EVEN LOOK at the value in the buffer.
In article <11*********************@i42g2000cwa.googlegroups. com>,
010 010 <of**************@gmail.comwrote:
>yes, i did. or rather, i put fread into a variable and then printed
that valiable. I kept geting 31.
Here are the arguments you showed for your fread() call in your
(not compile-able, so perhaps different from actual code) example:

fread(&newval,BPS,1,WavInPtr)

The fread() function takes four parameters:

- a pointer to the object(s) to be set (here &newval)
- the size of those objects (here BPS)
- the number of such objects (here 1)
- the file to read from (here WavInPtr)

The return value from fread() is the number of items successfully
read, which is always between 0 and the third argument inclusive.
Since your third argument is 1, fread() can only return either 0
or 1.

Hence, if you did:

x = fread(&newval, BPS, 1, WavInPtr);
printf("fread returned %d\n", x);

and found that x is 37, something is terribly, horribly wrong.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Oct 2 '06 #11
On 1 Oct 2006 14:13:50 -0700, "010 010" <of**************@gmail.com>
wrote:
>hey gordon,
>Did you also print the result of fread() after you called it?
If fread() returns 0 or -1, DON'T EVEN LOOK at the value in the buffer.

yes, i did. or rather, i put fread into a variable and then printed
that valiable. I kept geting 31.
>fread() returns an integer value. It cannot return "no return value at all".

I was pretty sure that this was the case. but since my integer that
fread was retuned into kept giving the same response, the two
possiblities were 1) fread keeps giving the same byte or 2) fread isnt
writing into the memory space of that variable.
It sounds like you're confusing the return value of the function with
the values put in your read buffer. The code you posted doesn't even
look at the function return value. Use something like:

int status;
status = fread( ...

Then check the value of status.
>The real question is still how does a call to ftell affect the way
fread works, either by affecting the file pointer, or some buffer or
something. atleast, thats what seems to me to be happening, because
adding and subtracting that one call to ftell drastically changes the
output of my program, and the input is not changing at all.

thanks
--
Al Balmer
Sun City, AZ
Oct 2 '06 #12
010 010 wrote:
>
Ancient_Hacker wrote:
[...]
I suspect fread is detecting end of file. Quite possible, if it did
hit end of file, or if you opened up the file in "text" mode.

Ah, i did open the file in text mode. Thank you for pointing that out.
This probably does affect things, however, it doesn't explain how a
call ftell allows the program to read all the way through the file. If
i had hit a data point that had the same bit pattern as an eof (which
it didn't, it hit decimal 31), would it continuoulsy return the same
byte or have no return value at all? or would it scroll off through
memory, reading the next consecutive bits?

Any insight into this quirk would be interesting to hear, thanks.
What was the byte _after_ the 31? Remember, fread will not fill the
buffer with the text-mode EOF character (ie: Ctrl-Z on Windows) if
it hits it. Rather, it will probably keep the previous character
(your "decimal 31") there.

My guess would be that ftell() is internally clearing the "I hit the
Ctrl-Z EOF marker" flag. (Does your program print two 31's at the
point that the ctrl-Z exists?)

Again, as was semi-sarcastically pointed out in Ancient_Hacker's
post, had you been checking the return from fread(), you would have
instead been asking the question "why does fread() claim I've hit
EOF when there are more bytes to read?"

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>
Oct 2 '06 #13
ok, ok.

Thanks all or the huge response. I apologize to ancient hacker, as i
thought he was talking about the return value of ftell. It is
obviously poor programing to not check the return of fread and just
accept the value in the buffer.

I haven't implemented any of these ideas yet, but i just wanted to say
that i'm on it, so ya'll can take a break from scrutinizing my
fragmented code. hopefully i'll have something better to post in the
next day or so.

also, thanks to shaggy for pointing out some of the finer (or not so
fine) points of posting readable code here.

I feel edified and appreciative: thanks,

010 010

Oct 2 '06 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Brady | last post by:
Hi, I'm having a problem reading and writing to a file. What I'm trying to do is read a file, modify the portion of the file that I just read, and then write the modified data back to the same...
2
by: Luc Holland | last post by:
Hey, I'm working on a program that reads a binary file. It's opened with ==== if ((f1=fopen(argv,"rb"))==NULL) { fprintf(stderr,"Error opening %s for reading . . .\n",argv); exit(2); } ====...
10
by: Alain Lafon | last post by:
Helas, I got something that should be a minor problem, but anyhow it isn't to me right now. A little code fragment: fread(&file_qn, x, 1, fp_q); The corresponding text file looks like...
6
by: Patrice Kadionik | last post by:
Hi all, I want to make a brief comparison between read() and fread() (under a Linux OS). 1. Family read and Co: open, close, read, write, ioctl... 2. Family fread and Co: fopen, fclose,...
2
by: Fernando Barsoba | last post by:
Hi all, I'm trying to read from a binary file, and I'm using 'fread()' as indicated in function 'getfile()'. The variable 'bytesread' shows that I have read the 557,000 bytes from the file, but...
2
by: Richard Hsu | last post by:
// code #include "stdio.h" int status(FILE * f) { printf("ftell:%d, feof:%s\n", ftell(f), feof(f) != 0 ? "true" : "false"); } int case1() { FILE * f = fopen("c:\\blah", "wb+"); int i = 5;
5
by: David Mathog | last post by:
When reading a binary input stream with fread() one can read N bytes in two ways : count=fread(buffer,1,N,fin); /* N bytes at a time */ or count=fread(buffer,N,1,fin); /* 1 buffer at a...
20
by: ericunfuk | last post by:
If fseek() always clears EOF, is there a way for me to fread() from an offset of a file and still be able to detect EOF?i.e. withouting using fseek(). I also need to seek to an offset in the file...
4
by: Giacomo | last post by:
Hello.. i'm using php on linux --version: PHP 5.2.5 (cli) (built: Apr 25 2008 18:40:41) Copyright (c) 1997-2007 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies and...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.