You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

55 lines
1.2 KiB

#include "assert.h"
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "unistd.h"
//Print binary
void printa(FILE *f, const char *s, const int len) {
char *out = (char*) calloc(len/8 + 1, sizeof(char));
for (int i = 0; i < len/8; ++i) {
for (int j = 7; j > -1; --j) {
out[i] += (s[8*i + (7-j)] - '0') << j;
}
}
fprintf(f, "%s", out);
free(out);
}
int main (int argc, char **argv) {
assert(argc == 3);
struct stat sbuf = {};
if (stat(argv[1], &sbuf) != 0) {
fprintf(stderr, "Error finding file\n");
return -1;
}
//Assume we can read the file
char *buff = (char*) malloc(sbuf.st_size * sizeof(char));
FILE *f = fopen(argv[1], "r");
if (f == NULL) {
fprintf(stderr, "Error opening input file\n");
return -1;
}
if (fread(buff, sizeof(char), sbuf.st_size, f) != sbuf.st_size) {
fclose(f);
fprintf(stderr, "Error reading file\n");
return -1;
}
//Close file when done reading
fclose(f);
f = fopen(argv[2], "w");
if (f == NULL) {
fprintf(stderr, "Error opening output file\n");
return -1;
}
printa(f, buff, sbuf.st_size);
return 0;
}