Trying to write a program in C, which I've never used before, to convert hexadecimal to binary as a string and write it to a file, The only problem is that it prepends to the output file when I want it to append. This occurs for both fprintf() and fputs().
This is the append code:
while(fgets(line,1024,inputFile)){
lineLen = strlen(line);
binary = hexToBin(line, lineLen);
printf("Binary: %s\n", binary);
// output file does not exist
FILE *writeFile = fopen(argv[2], "a");
if (writeFile == NULL) {
fprintf(stderr, "write file not found: %s\n", strerror(errno));
exit(1);
}
printf("appending binary to file\n");
fprintf(writeFile,"%s\n",binary);
printf("appended\n");
}
This is the hexToBin function:
char* hexToBin(char hex[], size_t len){
// convert hexadecimal to binary
char *binString = (char*)malloc(sizeof(char)*4*len);
for (int i=0;i<len;i++){
char *binNum = hexToBinHelp(hex[i]);
strcat(binString,binNum);
free(binNum);
}
return binString;
}
hexToBinHelp returns the hexadecimal character as a char* of it's binary representation (binNum=[0][0][0][0] for example). It's really long so I'd rather not put it here, but can if it would help.
When input file is:
000a
a000
Output file is:
1010000000000000
0000000000001010
Thanks
Your loop is calling fopen() every iteration, and never closing or flushing this file stream. Writes are buffered, waiting for the buffer to fill or be flushed or the file to be closed; so the next time you call fopen() you get the same pointer as the first time.
You're lucky it's not crashing. :) Do not call fopen() repeatedly. Call it once outside the loop, inside use or move the pointer over, and back outside call fclose().