473,769 Members | 6,926 Online
Bytes | Software Development & Data Engineering Community
+ 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(cons t 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("mem set:");
}

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

if(stat(FILENAM E,&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("mem set:");
}
}
printf("%d bytes has been read from the file.\n", count);
fclose(fp);
exit(EXIT_SUCCE SS);
}

void exit_error(cons t char* msg)
{
perror(msg);
printf("\n");
exit(EXIT_FAILU RE);
}

=============== ====== 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 3902
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(cons t 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("mem set:");
}

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

if(stat(FILENAM E,&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("mem set:");
}
}
printf("%d bytes has been read from the file.\n", count);
fclose(fp);
exit(EXIT_SUCCE SS);
}

void exit_error(cons t char* msg)
{
perror(msg);
printf("\n");
exit(EXIT_FAILU RE);
}

=============== ====== 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("fop en:");
}
<snip>
if(stat(FILENAM E,&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("mem set:");
}


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_Keit h) 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
2486
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 by the PHP gd2 Library. The problem is that im trying to translate the 'fread' structure into a MySQL blob reading, as follows:
2
15578
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
4192
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
19462
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:
22
1871
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
6322
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
3551
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
6354
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
30
14283
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
9589
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
9423
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,...
1
9996
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
9865
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
8872
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
6674
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
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3963
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
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.