473,883 Members | 1,705 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

about fwrite( )

how to use fwrite( ) instead of fprintf( ) in this case? I want to generate
binary file.

FILE *fnew;
int i, intName;
double array[500];

fprintf(fnew, "%d\n", intName);
fprintf(fnew, " %f", array[i]);
I know (I suppose) how to change the "intName" and "array[i]" using
fwrite( ) as follow:

fwrite(&intName , sizeof(int), 1, fnew);
fwrite(&array[i], sizeof(double), 1, fnew);

but how to hander the "\n" and " " using fwrite( )?
for example, how to handle this?

fprintf(fnew, " \n");
Nov 13 '05
23 17869
SomeDumbGuy <ab***@127.0.0. 1> wrote:
Josh Sebastian wrote:

FILE *fnew;
int i, intName;
double array[500];fwrite(&intN ame, sizeof(int), 1, fnew);
fwrite(&arra y[i], sizeof(double), 1, fnew);

fwrite(&intName , sizeof intName, 1, fnew);
fwrite(&array[i], sizeof array[i], 1, fnew);


Sorry to bother you.
In:

fwrite(&intNam e, sizeof (intName), 1, fnew);
fwrite(&arra y[i], sizeof (array[i]), 1, fnew);


Note: parantheses around these sizeof operands are redundant.
I understand why you changed the second one.
Is the first more for readability? Or for maintaince?


Both improve maintainability .

Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #11
"FrancisC" <fr**********@h ong-kong.crosswinds .net> wrote:
> how to use fwrite( ) instead of fprintf( ) in this case? I want togenerate > binary file.
Generating binary files has nothing to do with whether you use fwrite()
or fprintf(), and everything with whether you fopen() your output stream
as "w" ("write - text mode") or "wb" ("write - binary mode").
> FILE *fnew;
> int i, intName;
> double array[500];
>
> fprintf(fnew, "%d\n", intName);


So, how _did_ you fopen() fnew?

Richard


I use fnew = fopen(newFileNa me, "wb"), but I still can see the content
using notepad or other text editor, so i suppose it is ASCII,


Of course: you wrote text data to a file, what did you expect to see?
but I want to
generate binary file.


You already did; using fprintf, the binary data just happened to be
text. :-)

Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #12
> how to use fwrite( ) instead of fprintf( ) in this case? I want to

generate
> binary file.

Generating binary files has nothing to do with whether you use fwrite()
or fprintf(), and everything with whether you fopen() your output stream as "w" ("write - text mode") or "wb" ("write - binary mode").

> FILE *fnew;
> int i, intName;
> double array[500];
>
> fprintf(fnew, "%d\n", intName);

So, how _did_ you fopen() fnew?

Richard


I use fnew = fopen(newFileNa me, "wb"), but I still can see the content
using notepad or other text editor, so i suppose it is ASCII,


Of course: you wrote text data to a file, what did you expect to see?
but I want to
generate binary file.


You already did; using fprintf, the binary data just happened to be
text. :-)


Thats why I do not want to use fprintf( ) but fwrite( ).
To make all the "things" binary, am I just need to use fwrite( ) all the
times but not using fprintf() ?
I want the filesize as small as possible and as easy for the computer to
read as possible
Nov 13 '05 #13
> fwrite(&intName , sizeof(int), 1, fnew);
> fwrite(&array[i], sizeof(double), 1, fnew);

fwrite(&intName , sizeof intName, 1, fnew);
fwrite(&array[i], sizeof array[i], 1, fnew);


why use sizeof (intName) and sizeof (array[i]) instead of sizeof(int) and
sizeof(doubl e) ?
intName and array[] is set as int and double respectively
so are they both correct?


Both are correct, but the latter versions are easier to maintain. Think
about what happens if you decide to change the type of intName or array:
in the former versions you have to adjust the operand of sizeof, the
latter will nicely 'auto-adjust'.
> but how to hander the "\n" and " " using fwrite( )?
> for example, how to handle this?
>
> fprintf(fnew, " \n");

Why would you want to? The data is binary, so people aren't going to read it. Line formatting is pointless.

But, if you insist:

char s[] = " \n";
fwrite(s, sizeof s, 1, fnew);


I want to maintain a file structure for later reading from the binary file.So I think i need to, dont I?


No, you don't have to. What you have to do is remember the file
structure ("field width") when you read the file.

BTW, if you want your data files to be reliably portable between
different OSs/implementations you want to stick to the text file
approach (as binary data representations tend to vary across different
systems). Eventually converting text files (if necessary at all) is not
a big deal compared to, for example, translation between different
floating point representations .


thats mean if I want to store the file like this one (the integer is the no
of double no below):
3
100000.000000 200000.000000
300000.000000
4
100000.000000 200000.000000
300000.000000 400000.000000

in binary i should store like this with no space and new line?
3100000.0000002 00000.000000300 000.00000041000 00.000000200000 .000000300000.0 0
0000400000.0000 00

when I want to read the file, I use the code below??

while ( !feof(fnew) )
{
fread(&intName, sizeof (intName), 1, fnew);
/*determine the integer value, intVal. (i do not know how to write this
code yet)*/
fread(&doubleNo , sizeof (doubleNo), intVal, fnew);
}



Nov 13 '05 #14


FrancisC wrote:
BTW, if you want your data files to be reliably portable between
different OSs/implementations you want to stick to the text file
approach (as binary data representations tend to vary across different
systems). Eventually converting text files (if necessary at all) is not
a big deal compared to, for example, translation between different
floating point representations .

thats mean if I want to store the file like this one (the integer is the no
of double no below):
3
100000.000000 200000.000000
300000.000000
4
100000.000000 200000.000000
300000.000000 400000.000000

in binary i should store like this with no space and new line?
3100000.0000002 00000.000000300 000.00000041000 00.000000200000 .000000300000.0 0
0000400000.0000 00

when I want to read the file, I use the code below??

while ( !feof(fnew) )
{
fread(&intName, sizeof (intName), 1, fnew);
/*determine the integer value, intVal. (i do not know how to write this
code yet)*/
fread(&doubleNo , sizeof (doubleNo), intVal, fnew);
}


You have been warned that this it is not a portable to store these
values in a binary file. If you insist, here is how you might write
the code.

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

int main(void)
{
int count = 3, i;
double darray[3],dd;
FILE *fp;

if((fp = fopen("test.bin ","wb")) != NULL)
{ /* Create and write the int and double values to binary file*/
if(1 != fwrite(&count,s izeof count,1,fp)) exit(EXIT_FAILU RE);
for(i = 0;i < count;i++)
{
dd = i+1.0;
if(1 != fwrite(&dd,size of dd,1,fp)) exit(EXIT_FAILU RE);
}
fclose(fp);
/* Read and Test the Binary File */
if((fp = fopen("test.bin ","rb")) != NULL)
{ /* read the binary file */
if(1 != fread(&count, sizeof count,1,fp))
exit(EXIT_FAILU RE);
for(i = 0;i < dd;i++)
if(1 != fread(&darray[i], sizeof darray[i],1,fp))
exit(EXIT_FAILU RE);
fclose(fp);
}
}
/* print contents of binary file */
printf("Reading the binary file. there are %d \n"
"type double values in the file\nThery are:\n",count);
for(i = 0; i < count;i++)
printf("darray[%d] = %.2f\n",i,darra y[i]);
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.com base.com (remove the x)
http://www.geocities.com/abowers822/

Nov 13 '05 #15


FrancisC wrote:
BTW, if you want your data files to be reliably portable between
different OSs/implementations you want to stick to the text file
approach (as binary data representations tend to vary across different
systems). Eventually converting text files (if necessary at all) is not
a big deal compared to, for example, translation between different
floating point representations .
thats mean if I want to store the file like this one (the integer is the no
of double no below):
3
100000.000000 200000.000000
300000.000000
4
100000.000000 200000.000000
300000.000000 400000.000000

in binary i should store like this with no space and new line?
3100000.0000002 00000.000000300 000.00000041000 00.000000200000 .000000300000.0 0
0000400000.0000 00


In binary the above looks completely different, since numbers are stored
in the memory representation at the file. That's what binary means: no
translation when writing to the file, no translation when reading from
the file.

when I want to read the file, I use the code below??

while ( !feof(fnew) )
{
fread(&intName, sizeof (intName), 1, fnew);
/*determine the integer value, intVal. (i do not know how to write this
code yet)*/
fread(&doubleNo , sizeof (doubleNo), intVal, fnew);
}


No.
For 2 reasons:
* You don't use feof to control the loop. That's not what it is ment for.
feof() is used *after* you finish reading to check why the read has stopped.
if it was because of eof, then you have read the whole file. If it was not
because of eof, then some error has occoured.

* It is always a good idea to store some count in the file (just as you have
done it in the text version), that will guide the read process.

int count;
double numbers[100];

/* somehow you have filled the array with the numbers
** and stored a count of how many entries in the array
** you have used in count
**
** now write to file
*/
fwrite( &count, sizeof( count ), 1, fnew );
fwrite( numbers, sizeof( numbers[0] ), count, fnew );
...

/*
** and read from file
*/
fread( &count, sizeof( count ), 1, fnew );
fread( numbers, sizeof( numbers[0] ), count, fnew );
of course error checking needs to be added (use the return values
of fwrite and fread), but basically thats it.

--
Karl Heinz Buchegger
kb******@gascad .at
Nov 13 '05 #16
On Mon, 13 Oct 2003 11:08:45 -0400,
Josh Sebastian <cu****@cox.net > wrote:


Why would you want to? The data is binary, so people aren't going to read
it. Line formatting is pointless.

But, if you insist:

char s[] = " \n";
fwrite(s, sizeof s, 1, fnew);

Doing that will also write the terminating \0 character to the file.
That is fine if that is what you intend to do.

Villy
Nov 13 '05 #17
"FrancisC" <fr**********@h ong-kong.crosswinds .net> wrote:

[ Please do not snip attribution lines for quotes you leave in. While
you're at it, _do_ snip text you're not responding to. ]
but I want to generate binary file.
You already did; using fprintf, the binary data just happened to be
text. :-)


Thats why I do not want to use fprintf( ) but fwrite( ).
To make all the "things" binary, am I just need to use fwrite( ) all the
times but not using fprintf() ?


This makes no sense whatsoever. The data you have _is_ text. Writing it
using another function does not magically turn it into non-text. There
is _no_ difference between a byte written using fprintf() and the same
byte written using fwrite().
You seem to be rather confused as to what "binary data" actually is.
Have you considered the existence of the utility called "strings"? Have
you ever actually loaded a "binary" file into a text (or hex) viewer?
I want the filesize as small as possible and as easy for the computer to
read as possible


Those two requirements are mutually exclusive. To make the file as small
as possible, compress it. To make it easily readable, just output the
thing!

Richard
Nov 13 '05 #18
On Tue, 14 Oct 2003 08:31:45 +0800, in comp.lang.c , "FrancisC"
<fr**********@h ong-kong.crosswinds .net> wrote:

(lots of unattributed and untrimmed stuff)

Francis, some friendly advice: when responding to posts, please leave
the Attribution lines in (as above, the bit that says "FrancisC
wrote"), and trim your posts to remove irrelevant material.

Leaving in the attributions is important for people trying to follow a
thread, so you know who said which bit.
Trimming is important to ensure that posts to not become too long, and
relevant material appears in them.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #19
On Tue, 14 Oct 2003 08:09:40 +0800, in comp.lang.c , "FrancisC"
<fr**********@h ong-kong.crosswinds .net> wrote:
To make all the "things" binary, am I just need to use fwrite( ) all the
times but not using fprintf() ?


fwrite() dumps a block of memory to file. fprintf() prints formatted
data to a file, which might be text, or might not. Which do you want
to do?

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #20

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

Similar topics

3
2453
by: Antoine Bloncourt | last post by:
Hello everybody Sorry to bother you but I have a problem writing datas into a file ... I want to make a backup of my MySQL database and put the result into a ..sql file. To do this, I use the "get_table_strucure" and "get_table_content" functions.
3
6006
by: seia0106 | last post by:
Hello In the course of writing a program. I have to read and write a media file(*.avi/*.mpg/*.wav) to and from memory buffer. I can put the data(from a *.avi file)in buffer successfully but when i try to write data from buffer into a new file, then i can not play that file. A file size of only 4kb is copied and i can not play the file. The size of original file, whose contents were copied into buffer was 996KB. Can anyone please help...
5
3064
by: mhk | last post by:
Hi , is there any way to merge three sorted arrays into a sorted file, without using 4th array. i guess 3 way merge sort is the only option but i dont know its algorithem. can anyone tell me algorithm of 3 way merge sort or anyother way to solve this problem. Thank you veryyyyy much.
15
3917
by: Suraj Kurapati | last post by:
Hello, I'm having a rather strange bug with this code: for certain values of 'buf', a segmentation fault occurs when 'free(buf)' is followed by an 'fwrite()'. In the program output, there is no error reported by 'perror()' and the file is written correctly. /* returns NULL upon failure, or a calloc()ed data upon success */ char* recv_data(int *bytes_read);
4
2488
by: ibrahimover | last post by:
typedef struct{ char name; int no; }TAM; typedef struct{ char name; char ch; }HARF;
3
4542
by: sumit1680 | last post by:
Hi everyone, I am using the below listed code The code is #include<stdio.h> #include<stdlib.h> #include<string.h>
2
6325
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;
12
5110
by: hemant.gaur | last post by:
I have an application which writes huge number of bytes into the binary files which is just some marshalled data. int len = Data.size(); //arrary size for (int i = 0; i < len; ++i) fwrite(&Data, 1, 1, f); now after running this for long time and pushing millions of bytes, It once misses writing the last byte of fData. Then the further push of bytes is again correct. As i am not using the return value for the
25
15592
by: Abubakar | last post by:
Hi, recently some C programmer told me that using fwrite/fopen functions are not efficient because the output that they do to the file is actually buffered and gets late in writing. Is that true? regards, ...ab
0
9933
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
11123
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10836
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
10407
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
5794
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...
0
5982
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4606
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
4211
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3230
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.