473,461 Members | 2,029 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

An interesting thing about fread().

Hi, everyone. I noticed an interesting thing about fread() this
afternoon. Well, I can't see why so I post this message in the hope of
getting some explanation. Please help me.

I wrote the following code in Windows 2k and compiled it with the
gcc(version: 3.2.3) contained in MinGW:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#define FILENAME "test.txt"
#define BUFSIZE 1024

void exit_error(const char*);

int main(void)
{
FILE* fp = NULL;
int count = 0;
int rdbytes = 0;
int filesize = 0;
unsigned char buffer[BUFSIZE];
unsigned char* chptr = NULL;
struct stat st;

if ((chptr = memset(buffer, '\0', BUFSIZE)) == NULL)
{
exit_error("memset:");
}

if ((fp = fopen(FILENAME, "r")) == NULL)
{
exit_error("fopen:");
}

if(stat(FILENAME,&st)==0)
{
filesize=st.st_size;
printf("The size of this file is %d.\n", filesize);
}

while ((rdbytes = fread(buffer, sizeof(unsigned char), sizeof(buffer),
fp)) > 0)
{
printf("%d bytes is got.\n",rdbytes);
count += rdbytes;
if ((chptr = memset(buffer, '\0', BUFSIZE)) == NULL)
{
exit_error("memset:");
}
}
printf("%d bytes has been read from the file.\n", count);
fclose(fp);
exit(EXIT_SUCCESS);
}

void exit_error(const char* msg)
{
perror(msg);
printf("\n");
exit(EXIT_FAILURE);
}

===================== end of the code =======================
The result I got is displayed as follows:

The size of this file is 4976.
1024 bytes is got.
1024 bytes is got.
1024 bytes is got.
1024 bytes is got.
744 bytes is got.
4840 bytes has been read from the file.

===================== end of the result =======================

The interesting thing, I mean the question is
why the sum of the bytes that fread() read does not equal with the size
of the file?

Every time I use fread(), I always assume fread() could be reliable.
However, I can't trust fread() that much any more because of the above
code :(

Can anybody explain why that happened? Thanks very much.

Apr 13 '06 #1
6 3865
Claude Yih wrote:
Hi, everyone. I noticed an interesting thing about fread() this
afternoon. Well, I can't see why so I post this message in the hope of
getting some explanation. Please help me.

I wrote the following code in Windows 2k and compiled it with the
gcc(version: 3.2.3) contained in MinGW:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#define FILENAME "test.txt"
#define BUFSIZE 1024

void exit_error(const char*);

int main(void)
{
FILE* fp = NULL;
int count = 0;
int rdbytes = 0;
int filesize = 0;
unsigned char buffer[BUFSIZE];
unsigned char* chptr = NULL;
struct stat st;

if ((chptr = memset(buffer, '\0', BUFSIZE)) == NULL)
{
exit_error("memset:");
}

if ((fp = fopen(FILENAME, "r")) == NULL)
{
exit_error("fopen:");
}

if(stat(FILENAME,&st)==0)
{
filesize=st.st_size;
printf("The size of this file is %d.\n", filesize);
}

while ((rdbytes = fread(buffer, sizeof(unsigned char), sizeof(buffer),
fp)) > 0)
{
printf("%d bytes is got.\n",rdbytes);
count += rdbytes;
if ((chptr = memset(buffer, '\0', BUFSIZE)) == NULL)
{
exit_error("memset:");
}
}
printf("%d bytes has been read from the file.\n", count);
fclose(fp);
exit(EXIT_SUCCESS);
}

void exit_error(const char* msg)
{
perror(msg);
printf("\n");
exit(EXIT_FAILURE);
}

===================== end of the code =======================
The result I got is displayed as follows:

The size of this file is 4976.
1024 bytes is got.
1024 bytes is got.
1024 bytes is got.
1024 bytes is got.
744 bytes is got.
4840 bytes has been read from the file.

===================== end of the result =======================

The interesting thing, I mean the question is
why the sum of the bytes that fread() read does not equal with the size
of the file?

Every time I use fread(), I always assume fread() could be reliable.
However, I can't trust fread() that much any more because of the above
code :(

Can anybody explain why that happened? Thanks very much.

I tried your program. To me it works fine and I get the the same no of
bytes eitherways.

Apr 13 '06 #2
Claude Yih wrote:

snip
printf("The size of this file is %d.\n", filesize);
snip
printf("%d bytes has been read from the file.\n", count);
snip
The result I got is displayed as follows:

The size of this file is 4976.
1024 bytes is got.
1024 bytes is got.
1024 bytes is got.
1024 bytes is got.
744 bytes is got.
4840 bytes has been read from the file.


Which of those two totals matches the actual filesize in a directory
listing? Perhaps st.st_size is incorrect whilst fread(..) is returning
the correct number of bytes.

Apr 13 '06 #3
eml
I'm not sure about this, and please accept my apologies if I'm wrong.
But perhaps it has something to do with the NTFS-filesystem
and its fileheaders? I'm sorry again if im totally of track.

Apr 13 '06 #4
On 13 Apr 2006 03:15:48 -0700
"Claude Yih" <wi******@gmail.com> wrote:
Hi, everyone. I noticed an interesting thing about fread() this
afternoon. Well, I can't see why so I post this message in the hope of
getting some explanation. Please help me.

I wrote the following code in Windows 2k and compiled it with the
gcc(version: 3.2.3) contained in MinGW:
<snip>
#define FILENAME "test.txt"
<snip>
if ((fp = fopen(FILENAME, "r")) == NULL)
{
exit_error("fopen:");
}
<snip>
if(stat(FILENAME,&st)==0)
{
filesize=st.st_size;
printf("The size of this file is %d.\n", filesize);
}
<snip>
===================== end of the code =======================
The result I got is displayed as follows:

The size of this file is 4976.
1024 bytes is got.
1024 bytes is got.
1024 bytes is got.
1024 bytes is got.
744 bytes is got.
4840 bytes has been read from the file.

===================== end of the result =======================

The interesting thing, I mean the question is
why the sum of the bytes that fread() read does not equal with the size
of the file?

Every time I use fread(), I always assume fread() could be reliable.
However, I can't trust fread() that much any more because of the above
code :(

Can anybody explain why that happened? Thanks very much.


This is what you are looking for:

http://c-faq.com/stdio/textvsbinary.html

Magnus
Apr 13 '06 #5
Claude Yih wrote:

Hi, everyone. I noticed an interesting thing about fread() this
afternoon. Well, I can't see why so I post this message in the hope of
getting some explanation. Please help me.

I wrote the following code in Windows 2k and compiled it with the
gcc(version: 3.2.3) contained in MinGW: [...] ===================== end of the code =======================
The result I got is displayed as follows:

The size of this file is 4976.
1024 bytes is got.
1024 bytes is got.
1024 bytes is got.
1024 bytes is got.
744 bytes is got.
4840 bytes has been read from the file.

===================== end of the result =======================

The interesting thing, I mean the question is
why the sum of the bytes that fread() read does not equal with the size
of the file?

[...]

You have opened the file in text mode. Under Windows, a text file has
two characters for end-of-line (CR+LF -- "\r\n"), but the C library will
strip the CR when reading a file open in text mode, so that the program
will only see LF ('\n').

The stat() call is returning the "real" size if the file, while the
returns from fread() have stripped the CR.

If you were to examine the file, you would probably see that it has
136 (4976-4840) lines in it.

As a test, change the mode passed to fopen() from "r" to "rb", to open
the file in binary mode. Now, the CR's won't be stripped, and the
lengths will be equal.

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

Apr 13 '06 #6
"Claude Yih" <wi******@gmail.com> writes:
[...]
if ((chptr = memset(buffer, '\0', BUFSIZE)) == NULL)
{
exit_error("memset:");
}


memset() doesn't return NULL to indicate an error; in fact, it has no
mechanism for reporting errors. It just returns its first argument.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Apr 13 '06 #7

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

Similar topics

2
by: RootShell | last post by:
Dear All Im having some dificulty here: I found a great PHP code by Catalin Mihaila that reads a SRC (Sinclair Spectrum $SCREEN Image Format) and tranforms it into PNG format to show onscreen...
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,...
22
by: Rajshekhar | last post by:
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;
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;
13
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...
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...
30
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.
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...
1
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...
0
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...
0
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,...
0
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...

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.