473,563 Members | 2,695 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

write a binary file?

Dear all,

I open a binary file and want to write 0x00040700 to this file.
how can I set write buffer?
---------------------------------------------------
typedef unsigned char UCHAR;
int iFD=open(szFile Name,O_CREAT|O_ BINARY|O_TRUNC| O_WRONLY,S_IREA D|S_IWRITE);
UCHAR buffer[5]; //???????????
write(iFD,buffe r,5);
---------------------------------------------------

Thanks.

Regards,
cylin.
Nov 14 '05 #1
20 5562
"cylin" <cy***@avant.co m.tw> wrote:
I open a binary file and want to write 0x00040700 to this file.
how can I set write buffer?
Not like this, in ISO C. What you've got is system-specific, either
POSIX or not-quite-POSIX-M$.
typedef unsigned char UCHAR;
Yeugh.
int iFD=open(szFile Name,O_CREAT|O_ BINARY|O_TRUNC| O_WRONLY,S_IREA D|S_IWRITE);
Hungarian notation. Double yeugh. HN used to declare what everybody
reading your code, including the compiler, already knows: the types of
your identifiers. Triple yeugh, and go to the self-confidence shop and
buy some.
UCHAR buffer[5]; //???????????
Mixing declarations and executable statements is legal in C99 and C++,
but not in C89. Beware the snark.
write(iFD,buffe r,5);


No idea how to solve this using your low-level, unlikely-to-port
functions. In _real_ C, you'd do something like this:

#include <stdio.h>

unsigned char buf[5];
FILE *outfile;

if (!(outfile=fope n(filename, "wb")) {
puts("This is the place where you'd handle a file open error.");
} else {
if (fwrite(buf, sizeof *buf, sizeof buf/sizeof *buf, outfile) !=
sizeof buf/sizeof *buf) {
puts("Handle a write error here.");
}
/* Or, since you know that buf is an unsigned char array and
therefore sizeof *buf must be 1:
fwrite(buffer, 1, sizeof buf, outfile);
*/
fclose(outfile) ;
/* For critical applications, you should even check the return value
of fclose(), but I rarely do this. */
}

Issa dat si'ple.

Richard
Nov 14 '05 #2
"cylin" <cy***@avant.co m.tw> wrote:

I open a binary file and want to write 0x00040700 to this file.
how can I set write buffer?
Do you want to
[1] write bytes in exactly the order you gave above (portable
result), or
[2] write an unsigned long value to the file (non-portable
result)?
---------------------------------------------------
typedef unsigned char UCHAR;
int iFD=open(szFile Name,O_CREAT|O_ BINARY|O_TRUNC| O_WRONLY,S_IREA D|S_IWRITE);
UCHAR buffer[5]; //???????????
write(iFD,buff er,5);
---------------------------------------------------


Neither open nor write are standard C functions.
What you want is something like:

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
unsigned char buf[] = { 0x00, 0x04, 0x07, 0x00 };
unsigned long ul = 0x00040700UL;
FILE *fp;

if ( ( fp = fopen( "foo", "wb" ) ) != NULL )
{
fwrite( buf, sizeof buf, 1, fp ); /* [1] */
fwrite( &ul, sizeof ul, 1, fp ); /* [2] */
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}

HTH
Regards
--
Irrwahn Grausewitz (ir*******@free net.de)
welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
clc OT guide : http://benpfaff.org/writings/clc/off-topic.html
Nov 14 '05 #3
"cylin" <cy***@avant.co m.tw> writes:
Dear all,

I open a binary file and want to write 0x00040700 to this file.
how can I set write buffer?
Use shifts and mask operations (bitwise AND) to extract the individual
bytes. The details depend on the byte order in which you want to write
to the file.
---------------------------------------------------
typedef unsigned char UCHAR;
int iFD=open(szFile Name,O_CREAT|O_ BINARY|O_TRUNC| O_WRONLY,S_IREA D|S_IWRITE);
No such function in standard C. Use `fopen'.
UCHAR buffer[5]; //???????????
write(iFD,buffe r,5);
No such function in standard C. Use `fwrite'.
---------------------------------------------------


This program should give you same hints:
#include <stdlib.h>
#include <stdio.h>

int main (void)
{
const unsigned long value = 0x00040700;
unsigned char buffer [4];
FILE *f;

/* This as known as "big-endian" byte order. */
buffer [0] = value >> 24;
buffer [1] = (value >> 16) & 0xFF;
buffer [2] = (value >> 8) & 0xFF;
buffer [3] = value & 0xFF;

f = fopen ("testfile", "wb");
if (f != NULL)
{
if (fwrite (buffer, sizeof *buffer, sizeof buffer, f) < sizeof buffer
|| fclose (f) == EOF)
{
fputs ("Error writing to testfile.\n", stderr);
return EXIT_FAILURE;
}
}
else
{
fputs ("Cannot open testfile for writing.\n", stderr);
return EXIT_FAILURE;
}

return 0;
}
Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #4
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
if (fwrite(buf, sizeof *buf, sizeof buf/sizeof *buf, outfile) !=
sizeof buf/sizeof *buf) {
puts("Handle a write error here.");
}
fclose(outfile) ;
/* For critical applications, you should even check the return value
of fclose(), but I rarely do this. */


Why do you check the return value of `fwrite' then? Most operating
systems don't write immediately to the underlying device when `fwrite'
is called, but have some buffering mechanism. Therefore, an error is
far more likely to show up in `fclose' than in `fwrite' on such systems.

Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #5
Martin Dickopp <ex************ ****@zero-based.org> writes:
if (fwrite (buffer, sizeof *buffer, sizeof buffer, f) < sizeof buffer


That's inconsistent. Make that:

if (fwrite (buffer, 1, sizeof buffer, f) < sizeof buffer

Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #6
Great. Thank all.

I use low-level I/O functions because I want to the speed faster than
stardard I/O functions.
Can't low-level I/O functions do this case?

Regards,
cylin.
Nov 14 '05 #7
"cylin" <cy***@avant.co m.tw> writes:
I use low-level I/O functions because I want to the speed faster than
stardard I/O functions.
Can't low-level I/O functions do this case?


They can, but they're off-topic in comp.lang.c, which is only about
standard C.

<OT>
They are also harder to use correctly. Note, e.g., that it is not
necessarily an indication of error if the POSIX function `write' writes
less bytes than requested.
</OT>

Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #8
cylin <cy***@avant.co m.tw> scribbled the following:
Great. Thank all. I use low-level I/O functions because I want to the speed faster than
stardard I/O functions.
Can't low-level I/O functions do this case?


First of all, your "low-level I/O functions" might not even be available
on all platforms. Second of all, there is no guarantee they will be any
faster than standard I/O functions. They could even be slower.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"C++ looks like line noise."
- Fred L. Baube III
Nov 14 '05 #9
Martin Dickopp wrote:
"cylin" <cy***@avant.co m.tw> writes:
I open a binary file and want to write 0x00040700 to this file.
how can I set write buffer?
Use shifts and mask operations (bitwise AND) to extract the
individual bytes. The details depend on the byte order in which
you want to write to the file.

.... snip ...
This program should give you same hints:

#include <stdlib.h>
#include <stdio.h>

int main (void)
{
const unsigned long value = 0x00040700;
unsigned char buffer [4];
FILE *f;

/* This as known as "big-endian" byte order. */
buffer [0] = value >> 24;
buffer [1] = (value >> 16) & 0xFF;
buffer [2] = (value >> 8) & 0xFF;
buffer [3] = value & 0xFF;

f = fopen ("testfile", "wb");
if (f != NULL)
{
if (fwrite (buffer, sizeof *buffer, sizeof buffer, f) < sizeof buffer
|| fclose (f) == EOF)
{
fputs ("Error writing to testfile.\n", stderr);
return EXIT_FAILURE;
}
}
else
{
fputs ("Cannot open testfile for writing.\n", stderr);
return EXIT_FAILURE;
}

return 0;
}


There is nothing wrong with your code above, and it illustrates
most things admirably, I suggest that the use of embedded tests
will facilitate a clearer order of things. This is a style
question, not a flame, and just a suggestion. My version follows:

#include <stdlib.h>
#include <stdio.h>

int main (void)
{
const unsigned long value = 0x00040700;
unsigned char buffer [4];
FILE *f;

/* This as known as "big-endian" byte order. */
buffer [0] = value >> 24;
buffer [1] = (value >> 16) & 0xFF;
buffer [2] = (value >> 8) & 0xFF;
buffer [3] = value & 0xFF;

if (!(f = fopen("testfile ", "wb"))) {
fputs("Cannot open testfile for writing.\n", stderr);
}
else if ((fwrite(buffer , sizeof *buffer, sizeof buffer, f)
< sizeof buffer)
|| (EOF == fclose(f))) {
fputs("Error writing to testfile.\n", stderr);
}
else {
return 0;
}
return EXIT_FAILURE;
}

although the neophyte is still going to have trouble comprehending
the combined fwrite/fclose failure test. I have also added the
odd extraneous parentheses to make the meanings explicit.

This now follows the pattern "if phasefails exit else nextphase".

--
Some useful references:
<http://www.ungerhu.com/jxh/clc.welcome.txt >
<http://www.eskimo.com/~scs/C-faq/top.html>
<http://benpfaff.org/writings/clc/off-topic.html>
<http://anubis.dkuug.dk/jtc1/sc22/wg14/www/docs/n869/> (C99)
Nov 14 '05 #10

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

Similar topics

3
15656
by: kee | last post by:
Hi All, I am trying to write binary data to a file, which is bmp image: Open "d:\temp\test001.bmp" For Binary Access Write As #1 Put #1, 1, strImage Close #1 *** strImage contains binary data
4
3478
by: Jon Hyland | last post by:
Hi all, I'm looking for the fastest way to write (and/or read) binary to a file in VC++. I've been using the fstream object in this way: //unsigned char *pDataOut and long iLength initilized somewhere.. fstream file_out((const char *)pszOutFile, ios::in|ios::trunc|ios::binary);
1
1865
by: sleepylight | last post by:
I'm running into a strange problem with ostreams's write function. Please see the code below: ofstream save((job->b->get_filename()).c_str(), ios::out | ios::binary); if (!save) { cout << "Cannot open file" << endl; return; } else {
5
3647
by: philip | last post by:
Here is some lines of code than I wrote. You can copy/paste theis code as code of form1 in a new project. My problem is this one : I try to write in a file a serie of bytes. BUT some bytes written in file are not the sent bytes. Copy and paste the following lines to observe my problem. What can I do to resolve problem ? Only...
3
8522
by: Billy Smith | last post by:
I'm trying to write a little utility that will write some binary data to a file via a javascript and Windows Script Host under Windows XP. The only way to do this that I can find is to convert the binary data to text via String.fromCharCode() function and then write to the file with TextStream.Write(). But that function gives an "invalid...
6
7359
by: ericunfuk | last post by:
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...
2
3536
by: Thomi Aurel RUAG A | last post by:
Hy I'm using Python 2.4.2 on an ARM (PXA-270) platform (linux-2.6.17). My Goal is to write a list of bytes down to a file (opened in binary mode) in one cycle. The crux is that a '0x0a' (line feed) will break the cycle of one writing into several pieces. Writing to a "simple" file, this wouldn't cause any problem. Assuming - without...
13
18167
by: zach | last post by:
Can someone help me out, I can't figure out what I'm doing wrong to write to a file in binary mode. What's wrong with my code? <?php $fileName = "something.dat"; $string = "This is a string of text";
6
5232
by: aagarwal8 | last post by:
Hi, I am trying to write the contents of a textbox to a file in binary format. My code looks like this... private void btnWriteToFile_Click(object sender, EventArgs e) { FileStream fs = File.Open(@"D:\test.dat", FileMode.OpenOrCreate, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fs);
1
3894
by: =?Utf-8?B?U3RldmVU?= | last post by:
I have a structure that contains both 32x32 and 16x16 icons plus some text. I want to write all this to an XML file so that I can recover the icons later in an application. Can someone tell me how to properly serialize the System.Drawing.Icon structure to an XML file? The following code doesn't write the icon information to the xml file. ...
0
7664
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...
0
7583
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...
1
7638
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
7948
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...
1
5484
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
5213
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
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2082
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
1
1198
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.