Can someone please help me with converting txt file to binary. I have code that nicely opens the txt file reads it and displays it on the screen but I have problems trying to convert that txt file to binary and then appending new lines to it. Can someone please look at it and let me know how to do that. Code and explanation would really be appreciated.
Thanks in advance....
***********************************************************
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct human HUMAN;
struct human
{
char name[50];
char gender[10];
int age;
};
int main(void)
{
char c[50],tmpage[8];
FILE *file;
HUMAN *humans;
int num_humans = 0;
int i, j;
char *textFile = "flintstones.DAT";
file = fopen("flintstones.DAT", "r"
if(file==NULL)
{
printf("Error: can't open file.\n"
return 1;
}
else
{
while(fgets(c, 50, file)!=NULL)
{
if(num_humans==0)
{
humans = calloc(1, sizeof(HUMAN));
}
else
{
humans = realloc(humans, (num_humans+1)*sizeof(HUMAN));
}
for(i=0, j=0 ; c!='\t' ; i++, j++)
{
humans[num_humans].name[j] = c;
}
humans[num_humans].name[j] = '\0';
while (c=='\t' || c==' ') i++;
for(j=0 ; c!='\t' && c!=' ' ; i++, j++)
{
tmpage[j]=c;
}
tmpage[j]='\0';
humans[num_humans].age = atoi(tmpage);
while (c=='\t' || c==' ') i++;
for(j=0 ; c!='\0' ; i++, j++)
{
humans[num_humans].gender[j] = c;
}
humans[num_humans].gender[j] = '\0';
num_humans++;
}
fclose(file);
printf("*************** Current Age *****************\n"
for(i=0 ; i<num_humans ; i++)
{
printf("%s\t\t%d\t%s\t \n", humans.name, humans.age, humans.gender);
}
if(humans!=NULL)
{
free(humans);
}
return 0;
}
}
***********************************************************
Thanks in advance....
***********************************************************
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct human HUMAN;
struct human
{
char name[50];
char gender[10];
int age;
};
int main(void)
{
char c[50],tmpage[8];
FILE *file;
HUMAN *humans;
int num_humans = 0;
int i, j;
char *textFile = "flintstones.DAT";
file = fopen("flintstones.DAT", "r"
if(file==NULL)
{
printf("Error: can't open file.\n"
return 1;
}
else
{
while(fgets(c, 50, file)!=NULL)
{
if(num_humans==0)
{
humans = calloc(1, sizeof(HUMAN));
}
else
{
humans = realloc(humans, (num_humans+1)*sizeof(HUMAN));
}
for(i=0, j=0 ; c!='\t' ; i++, j++)
{
humans[num_humans].name[j] = c;
}
humans[num_humans].name[j] = '\0';
while (c=='\t' || c==' ') i++;
for(j=0 ; c!='\t' && c!=' ' ; i++, j++)
{
tmpage[j]=c;
}
tmpage[j]='\0';
humans[num_humans].age = atoi(tmpage);
while (c=='\t' || c==' ') i++;
for(j=0 ; c!='\0' ; i++, j++)
{
humans[num_humans].gender[j] = c;
}
humans[num_humans].gender[j] = '\0';
num_humans++;
}
fclose(file);
printf("*************** Current Age *****************\n"
for(i=0 ; i<num_humans ; i++)
{
printf("%s\t\t%d\t%s\t \n", humans.name, humans.age, humans.gender);
}
if(humans!=NULL)
{
free(humans);
}
return 0;
}
}
***********************************************************