/* 17oct07 John Pfeiffer packing bits in structs example
according to msdos prompt dir unpacked.txt is 24 bytes, packed.txt is 8 bytes
...of course with gcc packed becomes 4 bytes...
compiled with tcc... allowed me all sorts of irregular coding =)
compiled with gcc we had to clean up our malloc (add stdlib.h) and
use pointers (correct objects! :)
should use calloc? - for inialized to 0's? void* calloc(size_t elems, size_t bytes)
realloc for shrinking? - but if a new temp variable does not get the return value
then you could cause a memory leak...
NOTE: malloc needs to be error checked, if no free mem then returns NULL ptr...
Dangling pointer = Do not use the pointer after it has been freed, especially
do not "double free", set the ptr to NULL after freeing...
*/
#include <stdio.h>
#include <stdlib.h>
struct char_and_flags_unpacked
{
char character;
int a;
int b;
int c;
int d;
int e;
};
typedef struct
{
char character;
int a:1;
int b:1;
int c:1;
int d:1;
int e:1;
} char_and_flags_packed;
int main(int argc, char *argv[])
{
struct char_and_flags_unpacked* unpacked;
char_and_flags_packed* packed;
char dos_cmd[30];
FILE* fptru = fopen("unpacked.txt","w");
FILE* fptrp = fopen("packed.txt","w");
if( fptru == NULL )
{ printf("File Error unpacked.txt"); exit(1); }
if( fptrp == NULL )
{ printf("File Error packed.txt"); exit(1); }
unpacked = (struct char_and_flags_unpacked*) malloc( sizeof( struct char_and_flags_unpacked ) );
if (unpacked == NULL)
{ printf("Memory Error unpacked struct malloc"); exit(1); }
packed = (char_and_flags_packed*) malloc( sizeof(char_and_flags_packed) );
if (packed == NULL)
{ printf("Memory Error packed struct malloc"); exit(1); }
(*unpacked).character = 'a';
(*unpacked).a = 1;
(*unpacked).b = 1;
(*unpacked).c = 1;
(*unpacked).d = 1;
unpacked -> e = 1;
packed -> character = 'a';
packed ->a = 1;
packed ->b = 1;
packed ->c = 1;
packed ->d = 1;
packed ->e = 1;
fwrite( (char*) &unpacked, 1 , sizeof( struct char_and_flags_unpacked ), fptru );
fwrite( (char*) &packed, 1 , sizeof( char_and_flags_packed ), fptrp );
/* fflush( fptru); */
printf("This might print out the directory where the packed files are...\n");
strcpy(dos_cmd, "dir *.txt");
system(dos_cmd);
free(unpacked);
free(packed);
unpacked = NULL;
packed = NULL;
fclose(fptru);
fclose(fptrp);
return 0;
}