0
Why not writing all of the fields?!
I was learning about files in C and saw this code struct foo{ char x,y,z; }; int main(){ FILE *f=fopen("D:/f.bin", "wb"); struct foo bar; bar.x='t'; fwrite(&bar, sizeof(bar), 1, f); } it was mentioned that the value for y and z won't be stored in the file. and that's what actually happened when I tried it. I want to learn more about this but i couldn't find anything helpful. can you explain how this work, is it a compile-time or a run-time process, is there any other similar cases, is this just limited to structures?
5 Antworten
+ 1
Could it be that y and z are not written because they are empty? What are exact contents of your output file?
+ 2
Are you sure that you didn’t just overlook a few zeros or something in the file? Did you look at it with an hex editor?maybe the character got written but are not displayable?
This is not expected behavior as far as I know
Nope that shouldn’t happen. https://code.sololearn.com/c6EBvTcrz5jV/?ref=app incomplete initialization doesn’t change the size of the struct and we are writing everything between &bar and &bar+sizeof(bar) to the file. There should be random stuff in there
+ 1
Some more questions:
What compiler did you use which compiler flags, which os are you on ? Have you tried disassembling the executable and looking at what’s going on ?
0
@Max thanx for replying.
Yes, I'm sure there's only the value of x in the file, I've even tried assigning a value for y, and again only x and y values were stored but not z.
I'm running MinGw on windows, I'm running it from Code::blocks IDE, so I don't think there are any special flags. I'll install Cygwin and try testing it on GCC. however, I don't think it would make a difference.
And about the disassembling thing, I don't think I'll understand what would be written. I'm still a noob 😅😅
UPDATE:
Same on GCC.. only assigned variables are stored.
0
@BlazingMagpie Yup, that's it. local struct-type variables are initialized to zero by default. I tried it using malloc and the unassigned variables were stored with random values.
@Max that makes you right, there should be some zeros in the file, but it didn't occur to me because I was opening it using notepad. How stupid 🤦♂️