473,804 Members | 3,178 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

fread returns more than i want

Hello,

I have some problems with fread.. first, let's see a part of the source
file:

FILE *fp;
char buf[512];
size_t nread;
..
..
while( nread = fread(buf,1,siz eof(buf),fp) )
fwrite(buf,1,nr ead,stdout);

The code above is working fine, it returns a desired file on the screen.

Now the problem:
------------------
For a file server I need to give back a structure like: <
strcpy(result.t ext, buf) >;

For easier understanding, temporary I can also write:
< fprintf(stdout, buf) > instead of < fwrite(buf,1,nr ead,stdout) >.

But now at the end of each part of the file I get some strange characters
and the last block continues again
with the first lines of the file.

So, why does this happen and how can I solve the problem?

Thank's

Franz
Dec 4 '05 #1
9 2367
Franz Jeitler wrote:
For easier understanding, temporary I can also write:
< fprintf(stdout, buf) > instead of < fwrite(buf,1,nr ead,stdout)


No. fprintf() takes a zero-terminated string, while fwrite takes a buffer
of raw bytes. Further, fprintf() also looks at the string and interprets
it, which might not be the right thing.

Uli

Dec 4 '05 #2
Franz Jeitler wrote:
Hello,

I have some problems with fread.. first, let's see a part of the source
file:

FILE *fp;
char buf[512];
size_t nread;
..
..
while( nread = fread(buf,1,siz eof(buf),fp) )
fwrite(buf,1,nr ead,stdout);

The code above is working fine, it returns a desired file on the screen.

Now the problem:
------------------
For a file server I need to give back a structure like: <
strcpy(result.t ext, buf) >;

For easier understanding, temporary I can also write:
< fprintf(stdout, buf) > instead of < fwrite(buf,1,nr ead,stdout) >.

But now at the end of each part of the file I get some strange characters
and the last block continues again
with the first lines of the file.

So, why does this happen and how can I solve the problem?


I'm guessing here, as you didn't provide a complete program. fread()
does not terminate the buffer with a string terminator, so when you
strcpy() of fprintf(), you copy/write more characters than expected.

BTW, fprintf(stdout, buf) is a really bad idea,
fprintf(stdout, "%s", buf) is much better.
HTH
Bjørn
Dec 4 '05 #3
Franz Jeitler wrote:
[...]
For a file server I need to give back a structure like: <
strcpy(result.t ext, buf) >;

For easier understanding, temporary I can also write:
< fprintf(stdout, buf) > instead of < fwrite(buf,1,nr ead,stdout) >.

But now at the end of each part of the file I get some strange characters
and the last block continues again
with the first lines of the file.

So, why does this happen and how can I solve the problem?


You get a different interpretation if you regard buf as
a zero-terminated string than if you regard it as an array
of nread characters. In particular, if buf lacks a zero
terminator it is not a proper string, and passing it to
fprintf() invokes undefined behavior. (A likely result is
that fprintf() will "run off the end" of buf until it stumbles
upon a zero byte somewhere else in memory; you are probably
seeing the characters that precede that zero.)

Also, if '%' appears anywhere in buf, fprintf() will try
to interpret it as a formatting directive ...

Your best bet is to use fwrite(), as you apparently intend
to do eventually in any case.

--
Eric Sosman
es*****@acm-dot-org.invalid
Dec 4 '05 #4

"Ulrich Eckhardt" <do******@knuut .de> schrieb im Newsbeitrag
news:3v******** *****@uni-berlin.de...
Franz Jeitler wrote:
For easier understanding, temporary I can also write:
< fprintf(stdout, buf) > instead of < fwrite(buf,1,nr ead,stdout)


No. fprintf() takes a zero-terminated string, while fwrite takes a buffer
of raw bytes. Further, fprintf() also looks at the string and interprets
it, which might not be the right thing.

Uli


OK, I understand, so should I terminate the string manually (even if I
return a binary char-Array
in < result.text> ?

Franz
Dec 4 '05 #5

"Eric Sosman" <es*****@acm-dot-org.invalid> schrieb im Newsbeitrag
news:2t******** ************@co mcast.com...
Your best bet is to use fwrite(), as you apparently intend
to do eventually in any case.

--
Eric Sosman
es*****@acm-dot-org.invalid

Sorry, but I have to write the block into a structure for returning it to a
client, so what do you suggest?

Franz
Dec 4 '05 #6
Franz Jeitler wrote:
"Ulrich Eckhardt" <do******@knuut .de> schrieb im Newsbeitrag
news:3v******** *****@uni-berlin.de...
Franz Jeitler wrote:
For easier understanding, temporary I can also write:
< fprintf(stdout, buf) > instead of < fwrite(buf,1,nr ead,stdout)


No. fprintf() takes a zero-terminated string, while fwrite takes a
buffer of raw bytes. Further, fprintf() also looks at the string
and interprets it, which might not be the right thing.


OK, I understand, so should I terminate the string manually (even if I
return a binary char-Array
in < result.text> ?


No, use the right functions for whatever you are doing. If you have a
buffer containing text, that text will usually be followed by a null
character, if there isn't one, you might add it. If your buffer contains
other data, it might be perfectly possible that there is a null character
in the middle - functions only reading a buffer up to the first null char
are then not the suitable tool to handle such data.

Uli
Dec 4 '05 #7
Franz Jeitler wrote:
"Eric Sosman" <es*****@acm-dot-org.invalid> schrieb im Newsbeitrag
news:2t******** ************@co mcast.com...
Your best bet is to use fwrite(), as you apparently intend
to do eventually in any case.

--
Eric Sosman
es*****@acm-dot-org.invalid


Sorry, but I have to write the block into a structure for returning it to a
client, so what do you suggest?


What does the client expect to receive from you? If
the struct contains the bytes, like this:

struct {
size_t count;
char bytes[512];
} client_data;

.... then you can just read the data directly into the
struct, like this:

client_data.cou nt = fread(client_da ta.buf, 1,
sizeof client_data.buf , fp);

--
Eric Sosman
es*****@acm-dot-org.invalid
Dec 4 '05 #8

"Eric Sosman" <es*****@acm-dot-org.invalid> schrieb im Newsbeitrag
news:kJ******** ************@co mcast.com...
char bytes[512];
} client_data;

... then you can just read the data directly into the
struct, like this:

client_data.cou nt = fread(client_da ta.buf, 1,
sizeof client_data.buf , fp);

--
Eric Sosman
es*****@acm-dot-org.invalid


Oh yes, I think that might work, because my client code has < printf ("%s",
result.text) instead of < fread...>.

Thank you

Franz Jeitler
Dec 4 '05 #9
Franz Jeitler wrote:
"Eric Sosman" <es*****@acm-dot-org.invalid> schrieb im Newsbeitrag
news:kJ******** ************@co mcast.com...
char bytes[512];
} client_data;

... then you can just read the data directly into the
struct, like this:

client_data.c ount = fread(client_da ta.buf, 1,
sizeof client_data.buf , fp);

--
Eric Sosman
es*****@acm-dot-org.invalid

Oh yes, I think that might work, because my client code has < printf ("%s",
result.text) instead of < fread...>.


Aha! The client expects you to supply a zero-terminated
string, not a counted array of bytes. You should be using a
string-oriented input function like fgets(), not the array-
oriented fread().

--
Eric Sosman
es*****@acm-dot-org.invalid
Dec 4 '05 #10

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

Similar topics

4
6550
by: Meenakshi Matai | last post by:
I am trying to read data from a .dat file using fread. This is how my syntax looks: temp = fread(indata, sizeof(short int), 1, datafile); I looked into the data file in Hex format and saw that everytime fread finds the data "1A" it returns a non-zero value. I tried with another .dat file and the same thing happens. I went in and manually changed the contents of the .dat file.
2
618
by: Josh Wilson | last post by:
The fread() is what I believe is having trouble, but I do not know why. I know that the temp file is created and written to (and w/ the appropriate amount of data). fread() continues to return 0, but I don't know why it shouldn't work; but when I used ferror(stdin) and it gives 0 suggesting to me it read w/o problem, so I'm confused since I know there is information in the file, and it is allegedly reading from stdin, any help please? ...
4
7834
by: bill | last post by:
I am confused by the behavior of the following code. The function copy() takes two FILE *'s and copies the data from one to the other. In the main routine, I create a pipe and copy stdin to the write end while copying the read end to stdout. If the child handles copying the read end of the pipe to stdout, the main program returns. If the child handles copying stdin to the write end of the pipe, the parent hangs in copy(), blocking on...
13
3552
by: 010 010 | last post by:
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...
20
7552
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 frequently(forwards and backwards) and do fread() from that offset. Or better still, could anyone let me know some good ways to achieve what I need to do as above?Can I get hold of the file and being able to read in without using fread()? Using...
30
14289
by: empriser | last post by:
How to use fread/fwrite copy a file. When reach file's end, fread return 0, I don't konw how many bytes in buf.
2
5843
by: steve005 | last post by:
Hi, I am writing a binary file with matlab that consists of a couple hundred double values and then reading it in with c++. The problem arises in c++ when I try and read in the files. At a specific point it stops and wont read any more values. I use this code to open it and read it: if( (err = fopen_s( &fp,"C:/simfile1.tmg0" , "rb" )) != 0 ); fread(&coneAngle,sizeof(double),1,fp); After about twenty simmilar reads it fails, returns an...
20
2051
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) fread(&nscrdh,sizeof(nscrdh),1,in); fread(&data,sizeof(data),1,in); How can i know where the second fread start? Is it just start from the end of the first fread? Or somewhere else?
15
3190
by: =?ISO-8859-15?Q?L=E9na=EFc?= Huard | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello all, For some reasons, somewhere in a program, I'd like, if possible, to quickly parse a whole file before rewinding it and letting the full analysis start. My problem is that the FILE* I want do parse has been fopen'ed far away from where I am and I don't know in which MODE my FILE* has been opened. And additionally, my FILE* may not be a regular file, but a continuous
0
9584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10337
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10082
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9160
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6854
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4301
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3822
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2995
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.