473,713 Members | 6,107 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Very strange problem using FWRITE() to write data to a binary file

Hi everybody,
I'm facing a very very strange problem with a very very simple C
program...
My goal should be to write to a binary file some numbers (integers),
each one represented as a sequence of 32 bit.

I made this stupid trial code:

---------------------------------------------
FILE *fout;
int w;

main()
{
f_out = fopen("data_8bi t.bin", "wb");
if(f_out == NULL)
/* error signaling and exit */
else
{
w = 0x17070707;
fwrite(&w, sizeof(w), 1, f_out);
fclose(f_out);
}
}
---------------------------------------------

If I execute this code (compile with Visual Studio 6) and then open the
"data_8bit. bin" file (inside the Visual Studio), it is displayed as a
binary file, and I can see the data "07 07 07 17". It is correct.
Now, if in the code above I assign to w the value 0x07070707 (instead
of 0x17070707), execute the code and open the "data_8bit.bin" , it
contains no more binary data...
The same happens with 0x99999999, for example.

This behavior seems extremely strange to me... I think that the
fwrite() should work with any value of 32 bit assigned to the integer
w... but instead it shows an almost "random" (to me) behavior.

Can anyone help me?
Today I lost the whole day facing this problem, without making any step
forward.
Thank you a lot.
Best regards.

Claudio

Nov 14 '05 #1
6 8528
In article <11************ **********@g14g 2000cwa.googleg roups.com>,
<le******@yahoo .it> wrote:
:I'm facing a very very strange problem with a very very simple C
:program...

:If I execute this code (compile with Visual Studio 6) and then open the
:"data_8bit.bin " file (inside the Visual Studio), it is displayed as a
:binary file, and I can see the data "07 07 07 17". It is correct.
:Now, if in the code above I assign to w the value 0x07070707 (instead
:of 0x17070707), execute the code and open the "data_8bit.bin" , it
:contains no more binary data...
:The same happens with 0x99999999, for example.

This could be an artifact of whatever Visual Studio file viewer
facility you are using -- the viewer could be looking at the first
few bytes of the file to figure out what kind of file it is
and reacting differently for different sequences.
--
Disobey all self-referential sentences!
Nov 14 '05 #2
le******@yahoo. it wrote:
Hi everybody,
I'm facing a very very strange problem with a very very simple C
program...
My goal should be to write to a binary file some numbers (integers),
each one represented as a sequence of 32 bit.

I made this stupid trial code:
Try using a declared FILE *.
---------------------------------------------
FILE *fout; ^^^^ int w;

main()
{
f_out = fopen("data_8bi t.bin", "wb"); ^^^^^ f_out is not fout if(f_out == NULL)
/* error signaling and exit */ missing statement. This is *not* your test code. else
{
w = 0x17070707;
fwrite(&w, sizeof(w), 1, f_out);
fclose(f_out);
}
}
---------------------------------------------

If I execute this code (compile with Visual Studio 6) and then open the
"data_8bit. bin" file (inside the Visual Studio), it is displayed as a
binary file, and I can see the data "07 07 07 17". It is correct.
Now, if in the code above I assign to w the value 0x07070707 (instead
of 0x17070707), execute the code and open the "data_8bit.bin" , it
contains no more binary data...
The same happens with 0x99999999, for example.

This behavior seems extremely strange to me... I think that the
fwrite() should work with any value of 32 bit assigned to the integer
w... but instead it shows an almost "random" (to me) behavior.

Can anyone help me?


Try posting code that actually demonstrates your problem. The above
*cannot* be your code.

Try the following and see what happens. If you have problems with it,
complain to Microsoft.

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

int main(void)
{
FILE *tstfile;
unsigned long w[3] = { 0x17070707, 0x07070707, 0x99999999 };
unsigned long x;
const char fname[] = "data_8bit.bin" ;
size_t i;

printf("[output]\n");
for (i = 0; i < 3; i++) {
printf("Testing with %#010lx\n", w[i]);
if (!(tstfile = fopen(fname, "wb"))) {
printf("\"%s\" could not be opened for output.\n", fname);
exit(EXIT_FAILU RE);
}
if (fwrite(&w[i], sizeof w[i], 1, tstfile) == 1)
printf("one item written successfully\n" );
else {
printf("fwrite failed.\n");
exit(EXIT_FAILU RE);
}
fclose(tstfile) ;

if (!(tstfile = fopen(fname, "rb"))) {
printf("\"%s\" could not be opened for input.\n", fname);
exit(EXIT_FAILU RE);
}
if (fread(&x, sizeof x, 1, tstfile) == 1)
printf("one item read successfully\n" );
else {
printf("fread failed.\n");
exit(EXIT_FAILU RE);
}
printf("The value read was %#010lx.\n\n", x);
fclose(tstfile) ;
}
return 0;
}
[output]
Testing with 0x17070707
one item written successfully
one item read successfully
The value read was 0x17070707.

Testing with 0x07070707
one item written successfully
one item read successfully
The value read was 0x07070707.

Testing with 0x99999999
one item written successfully
one item read successfully
The value read was 0x99999999.


--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #3
le******@yahoo. it wrote:

I'm facing a very very strange problem with a very very simple C
program...
My goal should be to write to a binary file some numbers (integers),
each one represented as a sequence of 32 bit.

I made this stupid trial code:

---------------------------------------------
FILE *fout;
int w;

main()
{
f_out = fopen("data_8bi t.bin", "wb");
if(f_out == NULL)
/* error signaling and exit */
else
{
w = 0x17070707;
fwrite(&w, sizeof(w), 1, f_out);
fclose(f_out);
}
}
---------------------------------------------

If I execute this code (compile with Visual Studio 6) and then
open the "data_8bit. bin" file (inside the Visual Studio), it is
displayed as a binary file, and I can see the data "07 07 07 17".
It is correct. Now, if in the code above I assign to w the value
0x07070707 (instead of 0x17070707), execute the code and open the
"data_8bit.bin" , it contains no more binary data...
The same happens with 0x99999999, for example.


I fail to see how you can execute it - it won't even compile. If
you #include <stdio.h> and correct the name for the fout variable,
and include a return 0 at the end, and put something in for the
error branch, it works just fine.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson

Nov 14 '05 #4
On 8 Feb 2005 08:35:12 -0800,
le******@yahoo. it <le******@yahoo .it> wrote:

....
{
w = 0x17070707;
fwrite(&w, sizeof(w), 1, f_out);
fclose(f_out);
}
}
---------------------------------------------

If I execute this code (compile with Visual Studio 6) and then open the
"data_8bit. bin" file (inside the Visual Studio), it is displayed as a
binary file, and I can see the data "07 07 07 17". It is correct.
Now, if in the code above I assign to w the value 0x07070707 (instead
of 0x17070707), execute the code and open the "data_8bit.bin" , it
contains no more binary data...


Not strange at all. Keyword here is "little endian", where the least
significant byte of a multibyte integer is stored at the lowest memory
address, that is, occurs first in the disk file.
Villy
Nov 14 '05 #5
Walter is right, it is a problem of the Visual Studio viewer (I always
used it to display binary files, it's the first time it "betrays"
me)... In fact I downloaded a program that can display only the binary
format of files (no matter what kind of file it is), and I saw that the
data were written correctly, even those that Visual Studio didn't
display.

Sorry about the errors in the code I posted (no "stdio.h", mismatch
between "fout" and "f_out"), I did not copy&paste my code correctly (by
the way, the code I executed was without these errors).

Thank you all for your help, you saved me from losing another day of
work with this stupid problem ;-)

Best regards.
Claudio

Nov 14 '05 #6
Villy Kruse <ve*@station02. ohout.pharmapar tners.nl> writes:
On 8 Feb 2005 08:35:12 -0800,
le******@yahoo. it <le******@yahoo .it> wrote:

....
{
w = 0x17070707;
fwrite(&w, sizeof(w), 1, f_out);
fclose(f_out);
}
}
---------------------------------------------

If I execute this code (compile with Visual Studio 6) and then open the
"data_8bit. bin" file (inside the Visual Studio), it is displayed as a
binary file, and I can see the data "07 07 07 17". It is correct.
Now, if in the code above I assign to w the value 0x07070707 (instead
of 0x17070707), execute the code and open the "data_8bit.bin" , it
contains no more binary data...


Not strange at all. Keyword here is "little endian", where the least
significant byte of a multibyte integer is stored at the lowest memory
address, that is, occurs first in the disk file.


Endianness doesn't explain the problem he was seeing. If you write
the value 0x07070707 to a file, you should see consecutive bytes with
the value 0x07, regardless of byte order. He was seeing nothing
(which, as it turns out, was the fault of the tool he was using to
view the file).

--
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.
Nov 14 '05 #7

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

Similar topics

23
6763
by: deko | last post by:
Can someone point me to a sample script that will log all visitors to my web site? I'm looking for a simple script that will capture IP address, Host Name, Browser, OS, and referring page - and write that info to MySql. I've created a MySql database - visitors - with the columns mentioned above, but am fumbling trying to get started with PHP... any help is appreciated!
3
5999
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...
23
17845
by: FrancisC | last post by:
how to use fwrite( ) instead of fprintf( ) in this case? I want to generate binary file. FILE *fnew; int i, intName; double array; fprintf(fnew, "%d\n", intName); fprintf(fnew, " %f", array);
17
6118
by: SW1 | last post by:
I wrote a small program which does something like tftp - transfering files and some chat, anyway i got a problem with fwrite, here is a snippet of my code: while(length > 0) { putchar('.'); //These were for error checking if(length <= bsize) { //Buffer is bigger than remaining File realloc(buffer,length * sizeof(char)); //resize buffer to remain rec = recv(sock,buffer,length,0); //recieve Data
4
6866
by: welch | last post by:
while taking some rough disk performance measures on windows machines, and snooping with FileMon, i've noticed some odd behavior here's the little nul-writer i'm running: def writeTest(nBlocks, blockSize): """write nBlocks*blockSize nuls to a file""" f = open("writeTest.out", "wb") nulBlock = '\0'*blockSize while nBlocks: f.write(nulBlock)
4
3854
by: Nate Murray | last post by:
Hey all, I'm having a strange PHP (4.3.10) problem that seems to have something to do with javascript. This is a bit complex, so hold on to your hats. My issue is that a single function is wrongly being called twice. The weird part is that no "print" functions are being repeated, but any "lower" functions, such as fwrite or Pear::Mail::send are repeated twice. It is the strangest
5
1976
by: sweeet_addiction16 | last post by:
hello experts...pls help me debug this code........im not able to write in the data bytes ..only the few header bytes are written... #include<stdio.h> struct mthd_chunk { char id; unsigned long Length; /* This will be 6 */
11
4301
by: David Mathog | last post by:
In the beginning (Kernighan & Ritchie 1978) there was fprintf, and unix write, but no fwrite. That is, no portable C method for writing binary data, only system calls which were OS specific. At C89 fwrite/fread were added to the C standard to allow portable binary IO to files. I wonder though why the choice was made to extend the unix function write() into a standard C function rather than to extend the existing standard C function...
27
5113
by: Jeff | last post by:
Im trying to figure out why I cant read back a binary file correctly. I have the following union: #define BITE_RECORD_LEN 12 typedef union { unsigned char byte; struct { unsigned char type; /* 0 Type */ unsigned char sn; /* 1-3 Serial Number */
0
8795
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
9302
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...
0
7941
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
5942
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
4459
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
4714
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3154
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
2509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2101
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.