473,587 Members | 2,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

read and write binary file

Hi ALL,

I want to read a binary file(it's pic.tif file, I guess it's binary
file?), then write it to a new file), I have several questions about
this process:

When I use fread() to read a chunk of the file into a buffer, when it
encounters the end of the file, will the EOF indicator be put into the
buffer automatically just as an ordinary byte of the file, or do I
have to do it manually?

When I want to write chunks received to a new file, do I just write
each chunk sequentially until EOF? Do I need to append EOF to the new
file?

Suppose all chunks have been received and written to the new file,
then if I just name the new file with the correct extension, say
pic2.tif,will I be able to recover the original file like this?

I'm very new to C so your help is much appreciated.

Thanks in advance.

Mar 23 '07 #1
6 7360
ericunfuk wrote:
I want to read a binary file(it's pic.tif file, I guess it's binary
file?), then write it to a new file)
In general, all files are binary. There are some OSs that have special
textfiles, where the system transparently translates lineendings. As far
as C is concerned, there is also the distinction between using e.g.
fprintf() which does formatting (as text) before writing and fwrite, which
takes preformatted data.

When I use fread() to read a chunk of the file into a buffer, when it
encounters the end of the file, will the EOF indicator be put into the
buffer automatically just as an ordinary byte of the file, or do I
have to do it manually?
No, the value EOF is only used by e.g. fgetc() to signal that there was no
character to read. fread() signals how much was read directly and doesn't
use this signal value. Anyway, you typically can't store the EOF value in
a byte!
When I want to write chunks received to a new file, do I just write
each chunk sequentially until EOF? Do I need to append EOF to the new
file?
Again, EOF is not an can not be part of the file, therefore you don't write
it.
Suppose all chunks have been received and written to the new file,
then if I just name the new file with the correct extension, say
pic2.tif,will I be able to recover the original file like this?
Whether an extension is required and needed is up to your OS. Many OSs
don't need them to function.
I'm very new to C so your help is much appreciated.
Get a good book, check out the reviews at ACCU's website.

Uli
Mar 23 '07 #2
"ericunfuk" <xu***********@ gmail.comwrites :
When I use fread() to read a chunk of the file into a buffer, when it
encounters the end of the file, will the EOF indicator be put into the
buffer automatically just as an ordinary byte of the file, or do I
have to do it manually?
EOF is not a byte in a file and fread will not put it into a
buffer for you. Nor should you put it into the buffer yourself:
when converted to a character type, it will have the same value
as some other byte, so that later code will confuse that value
with an ordinary byte in the file.
When I want to write chunks received to a new file, do I just write
each chunk sequentially until EOF? Do I need to append EOF to the new
file?
EOF is not a byte in a file and you cannot write it to a file.
You can try to write it to a file, but in fact you will just
write an ordinary byte, and thus I do not recommend trying.
Suppose all chunks have been received and written to the new file,
then if I just name the new file with the correct extension, say
pic2.tif,will I be able to recover the original file like this?
You mean: if you copy the contents of one binary file accurately
to another, by using fread and fwrite, will the second file be
identical to the first? Ordinarily, yes: although I believe that
C allows the implementation to append any number of null bytes to
the second file, most implementations don't do that.
--
Comp-sci PhD expected before end of 2007
Seeking industrial or academic position *outside California* in 2008
Mar 23 '07 #3
>
No, the value EOF is only used by e.g. fgetc() to signal that there was no
character to read. fread() signals how much was read directly and doesn't
use this signal value. Anyway, you typically can't store the EOF value in
a byte!
When I want to write chunks received to a new file, do I just write
each chunk sequentially until EOF? Do I need to append EOF to the new
file?

Again, EOF is not an can not be part of the file, therefore you don't write
it.
I am confused.

Then how can I tell if there's no more bytes to read from?using feof()?
I tried a combination of fseek() and feof(), but there is the
possibility that when Igive fseek() an offset, it may seek over the
actual end of the file and reset EOF, thus the program never ends
because feof()can't find EOF?

I know I can use fread() to read from the start to the end without
fseek(), but I need to seek back and forth in case packets are lost
during transfer(I'm transferring a file using UDP, the client and
server are on the same machine for testing). Also the length of the
read buffer(or the length of my packet)is fixed, so what if the file
size is not an exact multiple of the buffer size, I'm doomed to seek
over EOF?

Eric
Mar 23 '07 #4
"ericunfuk" <xu***********@ gmail.comwrites :
Then how can I tell if there's no more bytes to read from?using feof()?
You just try to do a read. If the read doesn't return as many
bytes as you asked for, either an error occurred or you hit end
of file. You can use ferror() and feof() to figure out which one
happened.

Did you read the FAQ? The following question and answer might be
helpful.

12.2: Why does the code

while(!feof(inf p)) {
fgets(buf, MAXLINE, infp);
fputs(buf, outfp);
}

copy the last line twice?

A: In C, end-of-file is only indicated *after* an input routine has
tried to read, and failed. (In other words, C's I/O is not like
Pascal's.) Usually, you should just check the return value of
the input routine (in this case, fgets() will return NULL on end-
of-file); often, you don't need to use feof() at all.

References: K&R2 Sec. 7.6 p. 164; ISO Sec. 7.9.3, Sec. 7.9.7.1,
Sec. 7.9.10.2; H&S Sec. 15.14 p. 382.

--
"This is a wonderful answer.
It's off-topic, it's incorrect, and it doesn't answer the question."
--Richard Heathfield
Mar 23 '07 #5
if you are having problems with EOF you are probably not opening the
file in binary mode ("rb")

use FILE *fp=fopen("file ","rb");

also use when you use fread() you get the no .of bytes read till
EOF as the return value irrespective of the n passed ..
if no EOF is encountered Nis returned

use this n to write while using fwrite().

Mar 23 '07 #6
Ulrich Eckhardt wrote, On 23/03/07 16:13:
ericunfuk wrote:
>I want to read a binary file(it's pic.tif file, I guess it's binary
file?), then write it to a new file)

In general, all files are binary.
Not as far as C is concerned.
There are some OSs that have special
textfiles, where the system transparently translates lineendings.
There can be other differences as well, and this is why C makes a clear
distinction. You should therefore always open the file in the correct
mode unless you have a very good reason not to.
As far
as C is concerned, there is also the distinction between using e.g.
fprintf() which does formatting (as text) before writing and fwrite, which
takes preformatted data.
C does not make that distinction. C allows you to use fprintf on a
binary stream and fwrite on a text stream.

<snip>
>I'm very new to C so your help is much appreciated.

Get a good book, check out the reviews at ACCU's website.
Search the archives of this group and you will find references.
--
Flash Gordon
Mar 23 '07 #7

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

Similar topics

14
3756
by: spike | last post by:
Im trying to write a program that should read through a binary file searching for the character sequence "\name\" Then it should read the characters following the "\name\" sequence until a NULL character is encountered. But when my program runs it gets a SIGSEGV (Segmentation vioalation) signal. Whats wrong? And is there a better way...
8
30994
by: Patrik Malmström | last post by:
How do I read, write a file binary? I want to open, say, file.exe read it in to the program, then write it out to file2.exe. Like file copy, anyone have a code sample?
8
23895
by: a | last post by:
I have a struct to write to a file struct _structA{ long x; int y; float z; } struct _structA A; //file open write(fd,A,sizeof(_structA)); //file close
3
18958
by: nicolasg | last post by:
Hi, I'm trying to open a file (any file) in binary mode and save it inside a new text file. After that I want to read the source from the text file and save it back to the disk with its original form. The problem is tha the binary source that I extract from the text file seems to be diferent from the source I saved. Here is my code: 1)...
1
5473
by: vinothg | last post by:
I have a binary file,which contains strings of 30 bytes each.I need to open the file,read the strings one by one and if the string is not found i need to write it.But unfortunately both read and write using fstream is not not working.If i close the file and open it again it works. #include <iostream> #include <sys/stat.h> #include <fstream>...
3
2931
by: =?Utf-8?B?ZGF2aWQ=?= | last post by:
I try to follow Steve's paper to build a database, and store a small text file into SQL Server database and retrieve it later. Only difference between my table and Steve's table is that I use NTEXT datatype for the file instead of using IMAGE datatype. I can not use SqlDataReader to read the data. I need your help, Thanks. -David (1) I...
9
3838
by: vineeth | last post by:
Hello all, I have come across a weird problem, I need to determine the amount of bytes read from a file, but couldn't figure it out , My program does this : __ file = open("somefile") data = file.read() print "bytes read ", len(data) ---
5
11243
by: dm3281 | last post by:
Hello, I have a text report from a mainframe that I need to parse. The report has about a 2580 byte header that contains binary information (garbage for the most part); although there are a couple areas that have ASCII text that I need to extract. At the end of the 2580 bytes, I can read the report like a standard text file. It should have...
1
3922
by: Sachin Garg | last post by:
I have a program which opens a fstream in binary input+output mode, creating the file if it doesn't exists. But writing doesn't works after reading, it must be something obvious that I am not aware of. f.open(filename,ios::in | ios::out | ios::binary | ios::trunc) The program flow is 1) write some data 2) read the data
0
8205
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7967
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...
0
8220
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...
0
6619
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...
1
5712
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...
0
5392
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...
0
3840
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...
0
3872
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2347
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

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.