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); } 
6
  • 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? Commented Feb 27, 2014 at 5:57
  • There is missing a return statement in convertBase() function - resulting in "random" number written to your output file. Commented Feb 27, 2014 at 6:27
  • Where should I add the return statement? I think there may be something wrong with my snprintf statement... Commented Feb 27, 2014 at 6:49
  • convertBase() are sure this function working fine here. Because I can't find any logic here Commented Feb 27, 2014 at 6:56
  • No I'm not sure. But I've updated the code to what i'm currently concidering Commented Feb 27, 2014 at 7:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.