473,320 Members | 2,117 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,320 software developers and data experts.

question on fread()

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?

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 ?

thanks
Nov 14 '05 #1
5 2065
syntax <sa*****@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 (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"Make money fast! Don't feed it!"
- Anon
Nov 14 '05 #2
syntax wrote:

hi here is my test code

include<stdio.h>
#include<stdlib.h>

int main()

{
FILE *ptr1 = fopen("c:\\test1.txt","rb");
You opened in binary . . .
fread(b,9,4,ptr1);
Read in binary . . .
for(int k=0;k<6;k++)
printf("%d\n",b[k]);

}

test1.txt
----------
1 2 3 4 5
6 7 8 9 0

From a text file. Why did you think this would work? Does that look like
binary data to you?

Brian Rodenborn
Nov 14 '05 #3
> 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.


....ok, then in that way, it would be only usefull for printing,bcoz it
will read chars and print chars in the same way... i can not use that
for math operation!!

i think....
the real difficulty will come , if i read integers from the file using
FREAD()
AND then i try to increase each number by 1(i.e something like b[k]
= b[k] +1....its a math operation)....probabily i can not do it by
using fread() or can i?

is it too difficult to use fread() and do the math operation as i am
trying to do.

i can do it using fscanf()....but its a question to me whether fread()
can do it ??

N.B : i did a mistake ...the second argument and thrid argument should
be flipped...second argument should be = sizof (int)=4 , and third
argument = no of elements(9) want to read at one go.....anyway , still
my question remains same.

if fread() can not do these kind of math operation then what is the
importance of it!!!

any simple answer
Nov 14 '05 #4
[snips]
int b[50];

fread(b,9,4,ptr1);
Okay. This says "read 4 items of 9 bytes length, storing the data into b,
from file ptr1". First, I suspect you wanted to change the order around
to reading 9 items of 4 bytes, which, presumably, is the size of an int
on your implementation.

That said... the net result should be the same; that is, it should read 36
bytes from the file, storing them in ptr1. However, that's the kicker:
it's reading 36 bytes. Now let's see...

test1.txt
----------
1 2 3 4 5
6 7 8 9 0
1 has a value (in ASCII, which I'm assuming you're using) of 49. 2 has a
value of 50. Assuming those things in between are spaces, they'll have
values of 32. So your file is a set of byte values thusly:

[49][32][50][32][51][32]...
540155953
Okay, well, watch this:

unsigned char buff[4] = { 49, 32, 50, 32 };
printf( "Result: %d\n", *(int *)buff );

Any bets what the result is? On my machine - which apparently has the
same integer size, layout, etc as yours - I get the exact same value
displayed.
my question > how this output is coming ? why not the output is 1 2 3 4
5
6 ?
The problem is that you're not reading text and converting it to its
numeric representation. That is, you're not reading the characer '1' and
converting it to a value of 1. What you're doing is reading the charatcer
_code_ of the '1', along with the character code of the space, and so on,
then using those values as the values of the bytes in an int.

What you want to be doing is reading the _representation_ of the numbers
in the file (eg '1'), converting those to their numeric values (eg 1),
then storing those in the array.
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?
Hopefullly the explanation made some sense.
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 ?


You _can_ use fread to read a text file... but to do what you're doing,
it's the wrong tool. You might want to take a look at fscanf.
Nov 14 '05 #5
> Okay, well, watch this:

unsigned char buff[4] = { 49, 32, 50, 32 };
printf( "Result: %d\n", *(int *)buff );

Any bets what the result is?


I'd bet at 3:1 on a runtime error, unless you're using a compiler
that aligns char arrays (or a system that doesn't require int alignment)
Nov 14 '05 #6

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

Similar topics

51
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct...
21
by: siroregano | last post by:
Hi Everyone- I'm new to this group, and almost-as-new to asking programming questions publicly, so please forgive me if I miss a convention or two! I have a text file, around 40,000 lines...
7
by: Janice | last post by:
int* ptr; int i; fread(&i,sizeof(int),0L,fs); fread(ptr,sizeof(int),0L,fs); Which way of declaring the buffer for the fread is better? Thanx
5
by: NvrBst | last post by:
I have a bunch of variables I'd like to assign... is it possible to do it in 1 line. IE This is how I do it now int sally, jim, bill, fread, sam; sally = jim = bill = fread = sam = 5;
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...
10
by: Arquitecto | last post by:
Hi , I have a question about a file operation i want to do . I have a data file lets say X bytes . I want to read the file and delete a byte every 2nd byte . I am a little comfused ,my approach...
29
by: Bill Cunningham | last post by:
I wrote this small program to read a 512 block of binary data and write the same to a file. My code compiled well. The only thing is when I ran the compilers binary instead of a data file of 512...
20
by: xiao | last post by:
Hi~ every one~ I have a queston about fread function. if i have a code like this: (nscrdh and data are defined as two dementional arrays and both of them were stored in the same binary file) ...
2
by: Reeze | last post by:
Hi, everyone. I need your help! I created a UDP server by using $socket = stream_socket_server($udpAddr, $errno, $errstr, STREAM_SERVER_BIND); the client send me a reqest, then server return a...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.