I need to convert a text file of the following format to binary file. The input file only contains characters A, B, C or D. 'A' changes to '00','B' changes to '01', C changes to '10', D changes to '11'. Sample input file:
ABBCDA
BBAABCD
BACBB
Sample output file:
000101101100
01010000011011
0100100101
I have wrote the following code, but it doesn't work.
int main()
{
FILE * fop;
FILE * fout;
int length=0;
int i;
char buffer[1000];
fop = fopen("filename.txt","r");
fout = fopen("filename.bin", "wb");
while(!feof(fop))
{
fgets(buffer,1000,fop);
length = strlen(buffer)-1;
for(i=0; i<length; i++)
{
if(buffer[i]=='A')
strcpy(buffer[i],'00');
if(buffer[i]=='B')
strcpy(buffer[i],'01');
if(buffer[i]=='C')
strcpy(buffer[i],'10');
if(buffer[i]=='D')
strcpy(buffer[i],'11');
}
fwrite(buffer, 1, sizeof(char)*length, fout);
fwrite("\n",1,sizeof(char),fout);
}
fclose(fop);
fclose(fout);
return 0;
}
What's wrong? How to solve it? Thank you.