0

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);
kirbyfan64sos
  • 10,377
  • 6
  • 54
  • 75
  • 1
    The compiler has no idea whether the file your program opens is text or binary. The compiler's job is finished when it compiles your source code. It's completely out of the picture. Its job is done. Your question is unclear. – Sam Varshavchik Sep 22 '16 at 01:23
  • How to print the content to the screen. – James Johnson Sep 22 '16 at 01:29
  • `fopen(...,"r")` opens as text. `fopen(...,"rb")` opens as binary. Makes no difference on unix clones. On windows, the differences are the way newlines and Ctrl-Z are handled. Note that [while(!feof(fp)) is always wrong](http://stackoverflow.com/a/5432517/3386109). And you should always check the return value from `fopen`. It can fail and does fail, e.g. when the file doesn't exist. – user3386109 Sep 22 '16 at 01:31
  • Not just `CTRL-Z`. On MS-Windows, text files use the archaic `CRLF` newline sequence, and the text mode strips out the `CR`s; binary mode leaves them in. – Sam Varshavchik Sep 22 '16 at 01:37

0 Answers0