user3421311
user3421311

Reputation: 171

hexadecimal to decimal conversion

The first piece of code prints each line in b.txt in a new line when it outputs it, and the second code is the conversion from hexadecimal to decimal. I am bad at writing big programs, so I split the task and write smaller programs instead. I am having trouble combining these two programs. Can anyone help ?

#include <stdio.h>
int main ( int argc, char **argv ) 
{
    FILE *fp = fopen ( "b", "r");
    char line[1024];
    int ch = getc ( fp );
    int index = 0;
    while ( ch != EOF ) {
        if ( ch != '\n'){
            line[index++] = ch;
        }else {
            line[index] = '\0';
            index = 0;
            printf ( "%d\n", line );
        }
        ch = getc ( fp );
    }
    fclose ( fp );
    return 0;
}

This is the second program

  #include <stdio.h>
  #include <stdlib.h>

  int main()
  {
      unsigned int d;
      FILE *fp;
      FILE *ptr_file;
      fp = fopen("normal_data","r"); // read mode
      ptr_file =fopen("normal_decimal", "w");
      while(fscanf(fp,"%x", &d) == 1)
      {
          fprintf(ptr_file, "%d /n", d);
      }
      while( ( d = fgetc(fp) ) != EOF )
          fclose(fp);
      return 0;
  }

Upvotes: 0

Views: 274

Answers (1)

merlyn
merlyn

Reputation: 2361

It is good programming practice to split your program in small related fragments.

But instead of using a main function everywhere , try making functions which accomplish certain tasks and add them to a header file.

This will make it much easier to write, debug and re-use the code.

In the above case, converting hexadecimal to decimal is clearly something which maybe used again and again.

So, just make a function int hex_to_dec(char* input); which takes a string of input e.g,"3b8c" and converts it to a decimal and returns the converted value.

You may also want to make function void printFile(FILE* fp); which takes the pointer to a file and prints it data to stdout.

You can add these and other functions you have made, to a header file like myFunctions.h and then include the file into whatever program you need to use your functions in.

Upvotes: 1

Related Questions