473,847 Members | 1,420 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

fread()

Hi!
how many characters will be printed in output if our input file has
just 3 characters?
Sinppet Code :
#include<stdio. h>
main()
{
char buffer[1024];
char input[] = "some file"
FILE *fp = fopen(input , "r");
int c = fread(buffer , 1 , 1024, fp);
int i = 0;
for(i = 0 ; buffer[i]!=EOF ; ++i)
printf("%c" , buffer[i]);
fclose(fp);
}
the result for me is my 3 input characters in file plus lots of
strange characters why?
does fread consider EOF while reading from file?
Thanks!
Jan 23 '08 #1
6 15900
h03Ein wrote:
Hi!
how many characters will be printed in output if our input file has
just 3 characters?
Sinppet Code :
#include<stdio. h>
main()
{
char buffer[1024];
char input[] = "some file"
FILE *fp = fopen(input , "r");
I hope you actually check that the above call succeeded?
int c = fread(buffer , 1 , 1024, fp);
int i = 0;
Mixed declarations and code are new to C99, which isn't implemented
widely yet.
for(i = 0 ; buffer[i]!=EOF ; ++i)
printf("%c" , buffer[i]);
fclose(fp);
}
the result for me is my 3 input characters in file plus lots of
strange characters why?
does fread consider EOF while reading from file?
No. It returns the count of characters that it actually read, which may
be less than what you asked it for or zero. To find out if it was
end-of-file or an error that was responsible for the short count you
must use feof() or ferror() after the fread() call.

Specifically in the above for loop you must consider only the first 'i'
characters of buffer as valid.

Jan 23 '08 #2

"h03Ein" <ho************ @gmail.comwrote in message
Hi!
how many characters will be printed in output if our input file has
just 3 characters?
Sinppet Code :
#include<stdio. h>
main()
{
char buffer[1024];
char input[] = "some file"
FILE *fp = fopen(input , "r");
int c = fread(buffer , 1 , 1024, fp);
int i = 0;
for(i = 0 ; buffer[i]!=EOF ; ++i)
printf("%c" , buffer[i]);
fclose(fp);
}
the result for me is my 3 input characters in file plus lots of
strange characters why?
does fread consider EOF while reading from file?
Thanks!
fread() will stop reading when it encounters EOF.
The return value is the number of items read successfully, and anything
afterwards is garbage - in your case, strange characters.
The EOF is not itself placed into the buffer and is in any case an integer.
If you think about it, it is necessary for EOF to be wider than a character,
if every character is to be representable.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jan 23 '08 #3
Malcolm McLean wrote:
>
"h03Ein" <ho************ @gmail.comwrote in message
>Hi!
how many characters will be printed in output if our input file has
just 3 characters?
Sinppet Code :
#include<stdio .h>
main()
{
char buffer[1024];
char input[] = "some file"
FILE *fp = fopen(input , "r");
int c = fread(buffer , 1 , 1024, fp);
int i = 0;
for(i = 0 ; buffer[i]!=EOF ; ++i)
printf("%c" , buffer[i]);
fclose(fp);
}
the result for me is my 3 input characters in file plus lots of
strange characters why?
does fread consider EOF while reading from file?
Thanks!
fread() will stop reading when it encounters EOF.
<pedantic>
When it encounters end-of-file condition. EOF is the object like macro
used to signal end-of-file /or/ error to user code, and it is /not/
used by fread().
</pedantic>

<snip>

Jan 23 '08 #4
h03Ein wrote:
Hi!
how many characters will be printed in output if our input file has
just 3 characters?
Sinppet Code :
#include<stdio. h>
main()
{
char buffer[1024];
char input[] = "some file"
FILE *fp = fopen(input , "r");
You should verify that it succeeds:
if (fp == NULL) {
perror("Cannot open file");
exit(EXIT_FAILU RE);
}
or whatever is appropriate. exit and EXIT_FAILURE are declared/defined in
stdlib.h.
int c = fread(buffer , 1 , 1024, fp);
fread returns a size_t. You're using 1024 bytes, and int is required to
hold numbers to 32767, so, in this case, it is OK, but, in general, I
would use a size_t. Also, decimal constants ("magic numbers") tend to make
programs harder to understand. Use sizeof buffer in place of 1024 on that
line. Or use #define BUFFERSIZE 1024, declare buffer as `char
buffer[BUFFERSIZE]`, and use fread(buffer, 1, BUFFERSIZE, fp);
int i = 0;
for(i = 0 ; buffer[i]!=EOF ; ++i)
Make it: (see below)
for (i = 0; i < c; i++)
printf("%c" , buffer[i]);
Why? putchar(buffer[i]) would do that. Do you use a hammer to plant
drawing pins?
BTW, you could just use fwrite(buffer, 1, c, stdout); to do the same thing.
fclose(fp);
}
the result for me is my 3 input characters in file plus lots of strange
characters why?
EOF is a negative integer. If char is signed, that loop will stop when
hitting a valid character, e.g. ÿ. If it is unsigned, it will go on until
the end of the memory you're allowed to read, and then the behavior is
undefined. See www.c-faq.com, section 12.
does fread consider EOF while reading from file?
It returns the numbers of characters successfully read, so the loop should
be changed as above.

--
Army1987 (Replace "NOSPAM" with "email")
Jan 23 '08 #5
In article <fn**********@r egistered.motza rella.org>,
santosh <sa*********@gm ail.comwrote:
>h03Ein wrote:
>Hi!
how many characters will be printed in output if our input file has
just 3 characters?
Sinppet Code :
#include<stdio .h>
main()
{
char buffer[1024];
char input[] = "some file"
FILE *fp = fopen(input , "r");

I hope you actually check that the above call succeeded?
> int c = fread(buffer , 1 , 1024, fp);
int i = 0;

Mixed declarations and code are new to C99, which isn't implemented
widely yet.
I don't see any mixed declarations and code here. A bunch of
initializations that would be better done after the declarations, yes,
but all the executable code above this point is in the
initializations .

If he was mixing declarations and code, he'd have a program that was
not valid under any C standard, since he's implicit-inting main (which
went away in C99).
dave

--
Dave Vandervies dj3vande at eskimo dot com
Why does all this bother you with parachutes and not with cars? Many cars
can take you past terminal velocity.
--Maarten Wiltink in the scary devil monastery
Jan 23 '08 #6
h03Ein wrote:
>
how many characters will be printed in output if our input file
has just 3 characters?

Sinppet Code :
#include<stdio. h>
main() {
char buffer[1024];
char input[] = "some file"
FILE *fp = fopen(input , "r");
int c = fread(buffer , 1 , 1024, fp);
int i = 0;
for(i = 0 ; buffer[i]!=EOF ; ++i)
printf("%c" , buffer[i]);
fclose(fp);
}
the result for me is my 3 input characters in file plus lots of
strange characters why? does fread consider EOF while reading
from file?
Yes, but it is a characteristic of the streamed device, not of the
char stream. The value in c should be 3 if only 3 chars were
read. What you have in buffer is not a string, because it lacks a
final '\0'.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Jan 24 '08 #7

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

Similar topics

2
15579
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); } ==== The structure of the file is:
10
4201
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 this: 456 5 1.txt%&'
6
19472
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, fread, swrite, fcntl... Family read and Co:
2
6324
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;
8
17197
by: M. Åhman | last post by:
I'm reading "C: A Reference Manual" but still can't understand a very basic thing: is there any functional difference between fgetc/fputc and fread/fwrite (when reading/writing one unsigned char)? 1. Books and documentation on C tell me fread and fwrite is "binary". What does binary mean in this? Anything to do with opening a file in binary mode? 2. I'm also sure I've read somewhere on the net that fread and
13
3554
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...
5
6358
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 time */ I would assume the latter form would be faster, or at least
20
7557
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...
3
4599
by: juleigha27 | last post by:
Hi, First off, I want to apologize if this already got posted it seemed like something happened when I tried to post it previously and it didn't work. I am new to file manipulation with c. I am trying to read in a file and then parse it to assign the value to variables. I have read that fread is more is better for this then fscanf, so I tried the following code with the input file and resulting output:
30
14291
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.
0
9892
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9734
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
10653
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...
1
10718
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9490
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...
1
7888
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5725
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
4540
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
3
3168
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.