Included is the main and then the implementation of the hex and binary dump, my main concern is with the main. The code is in C. It compiles without error. Im being told to add more details because the post is mostly code but i thought i got my point across. Im looking for whatever is causing the segmentation fault.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "xbd.h"
#include "xbd.c"
int main(int argc, char *argv[]){
int i;
int counter = 0;
char *addy;
char buffer[16];
//If the user wishes for binary output command arg 2 will be '-b'
if(strcmp(argv[1], "-b") == 0){
FILE *f = fopen(argv[2], "r");
addy = (char*) f;
//Check for valid file
if(f == NULL){
printf("Error: File Empty.\n");
return(-1);
}
//print starting address, faults before this print
printf("%p: ", (void*)&f);
while((i = fgetc(f)) != EOF){
//While there are contents in the file, dump in binary groups of 6 chars
if(counter == 6){
//print human readable string here
printf(" ");
for(int i = 0; i < 6; i++){
printf("%s", buffer[i]);
}
printf("\n");
printf("%p: ", (void*)&addy);
counter = 0;
}
buffer[counter] = binForm(i);
counter++;
addy++;
}
fclose(f);
}
//If not binary, output will be in Hex
else{
FILE *f = fopen(argv[1], "r");
//addy = (char*) f;
//Check for valid file
if(f == NULL){
printf("Error: File Empty.\n");
return(-1);
}
//Print starting address, faults before this print
printf("%p: ", (void*)&f);
while((i = fgetc(f)) != EOF){
//While file has contents, dump in hex groups of 16 chars
if(counter == 16){
printf(" ");
//print human readable string here
for(int i = 0; i < 16; i++){
printf("%s", buffer[i]);
}
printf("\n");
printf("%p: ", (void*)&addy);
counter = 0;
}
if(counter%2 == 1){
buffer[counter] = hexForm(i);
printf(" ");
}
else{
buffer[counter] = hexForm(i);
}
counter++;
addy++;
}
fclose(f);
}
}
char hexForm(int current_byte){
//Print hex digits for one byte
printf("%X", current_byte);
//If unprintable, convert to '.'
if(current_byte < 33)
current_byte = 46;
return (char)current_byte;
}
char binForm(int current_byte){
//Print binary digits for one byte
while (current_byte) {
if (current_byte & 1)
printf("1");
else
printf("0");
current_byte >>= 1;
}
//If unprintable, convert to '.'
if(current_byte < 33)
current_byte = 46;
return (char)current_byte;
}
Why is it faulting? I tried commenting some of the early stuff out to see if it goes through but the first couple lines of code result in seg fault. The purpose of the program is to read a file and then changed the text to hex or binary coded output depending on command line argument "-b".