0

I keep recieving a bus error when trying to write to my output file. my binary function converts incoming text, from the input file, to binary and puts it in the output file. But I keep getting this bus error when I run, and I do not know why!

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

#define MAXLEN 255
#define FLAG 1
#define INPUT 2
#define OUTPUT 3

int binary(unsigned char x){ //, int argc, char* argv[]){
  FILE* out;

  unsigned char i, n = (sizeof(x) * CHAR_BIT) -1;
  int t;
  for(i=0; i<= n; i++){

    fprintf(out, "%d",(x >> (n-i) & 1));
  }
  fprintf(out, " \n");
}

int main(int argc, char *argv[]){

  FILE *in, *out;
  char instring[MAXLEN];
  const char *p;

  in = fopen(argv[INPUT], "r");
  if(in == NULL){
    printf("Error: This File is Empty.\n");
    exit(1);
  }else{
     out = fopen(argv[OUTPUT], "w");

  if(strcmp(argv[FLAG], "-b") == 0){
    fgets(instring, MAXLEN, in);

    for(p = instring; *p != '\0'; p++){
      // fprintf(out, "%d", binary(*p));
      binary(*p);
  }
 }
   else
   if(strcmp(argv[FLAG], "-t") == 0){

  }

   else{
    printf("Error: Flag Not Recognized.\n");
    return 0;
   }
 }
  fclose(in);
  fclose(out);
}
Ted
  • 3
  • 3
  • I looked at that entry and came up with this line of replacement code: snprintf(s, MAXLEN, "%d", 2); And the result in my output file is this: -4195864 Any advice as to why? – Ted Feb 27 '14 at 05:57
  • There is missing a `return` statement in `convertBase()` function - resulting in "random" number written to your output file. – petrch Feb 27 '14 at 06:27
  • Where should I add the return statement? I think there may be something wrong with my snprintf statement... – Ted Feb 27 '14 at 06:49
  • `convertBase()` are sure this function working fine here. Because I can't find any logic here – Sanoob Feb 27 '14 at 06:56
  • No I'm not sure. But I've updated the code to what i'm currently concidering – Ted Feb 27 '14 at 07:00
  • `fprintf(out, "%d\n", convertBase(instring));` to `for(i=0;instring[i];++i)fprintf(out, "%d\n", (int)instring[i]);` – BLUEPIXY Feb 27 '14 at 10:57

0 Answers0