was trying to write some c code to read a text file which contains some hex value in the follow format
AA
BB
CC
DD
Containing 1 Byte of hex values per line in the file.
the following is the code I used to attempt to read 1 byte of Hex values per read
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char* file_path;
FILE *fp;
uint8_t tmp_hex;
char buf[1L<<15];
int main (){
file_path = "./hex.txt";
printf("0\n");
fp = fopen(file_path, "rb");
printf("1\n");
fscanf(fp, "%02X\n", tmp_hex);
printf("2\n");
*buf = tmp_hex;
}
the code seems to work up to print("1\n");
since 1 is the last thing I see printed in terminal before I receive an error message segmentation fault (core dumped)
what am I doing wrong when reading the text file?
The end goal is to read every byte in the text file and store into buf
for binary manipulation
fscanf(fp, "%02X\n", tmp_hex);
You need to pass a reference to an unsigned int
variable. So you have 2 UBs in this line of code:
tmp_hex
has the wrong type.If fp
is NULL
it will invoke another UB.
You want: fscanf(fp, "%2hhX", &tmp_hex);
You should also check the result of I/O operations as they may fail.