I am trying to practice file I/O. I am trying to write a program that reads any file (text or binary) and prints contents in both hexadecimal and ascii. The problem is I am trying to figure out how the compiler knows the file is text or binary. The code I presented below converts binary to hexadecimal. I am also not sure on how to print the desired output to the screen. I've experimented with put function but it causes alot of bugs in the program. Any ideas about how the compiler will know if the file is text or binary. I think we can use an if statement but I'm not sure.
#include <stdio.h>
int main(int argc, const char * argv[]) {
FILE * file;
file = fopen( "test.txt" , "r");
char textFile[1000];
while (!feof(file)) {
fgets(textFile, 1000, file);
char binaryNumber[1000],hexaDecimal[1000];
int temp;
long int i=0,j=0;
while(binaryNumber[i]){
binaryNumber[i] = binaryNumber[i] -48;
++i;
}
--i;
while(i-2>=0){
temp = binaryNumber[i-3] *8 + binaryNumber[i-2] *4 + binaryNumber[i-1] *2 + binaryNumber[i] ;
if(temp > 9)
hexaDecimal[j++] = temp + 55;
else
hexaDecimal[j++] = temp + 48;
i=i-4;
}
if(i ==1)
hexaDecimal[j] = binaryNumber[i-1] *2 + binaryNumber[i] + 48 ;
else if(i==0)
hexaDecimal[j] = binaryNumber[i] + 48 ;
else
--j;
printf("Equivalent hexadecimal value: ");
while(j>=0){
printf("%c",hexaDecimal[j--]);
}
return 0;
}
}
fclose(file);