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); }
returnstatement inconvertBase()function - resulting in "random" number written to your output file.convertBase()are sure this function working fine here. Because I can't find any logic here