I want to read a file (plain text) and see if it contains 12 bytes of data, starting with "CLOSE" and end with "SCDH". I am using memcpy
to copy over the buffer string in order to compare consecutive memory address. However, the resulting buffer, buffer_two
has an extra \377
at the end. The other variable buffer
is able to print out CLOSE
if the passing file contains it. I am not sure why I got the extra character for buffer_two
.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE *f = fopen(argv[1], "r");
int size;
fseek(f, 0, SEEK_END);
size = ftell(f);
rewind(f);
char *temp = malloc(sizeof(char) * size);
fread(temp, sizeof(char), size, f);
int i;
for (i = 0; i < size - 12; ++i) {
if (temp[i] == 'F') {
char buffer[4];
char buffer_two[4];
memcpy(buffer, &temp[i], 4*sizeof(char));
memcpy(buffer_two, &temp[i+8], 4*sizeof(char));
printf("buffer %s\n", buffer);
printf("buffer_two %s\n", buffer_two);
if (memcmp(buffer, "CLOSE", 4) == 0 && memcmp(buffer_two, "SCDH", 4) ==0) {
return 1;
}
}
}
return 0;
}
Here is the output from GDB after memcpy
(gdb) print buffer_two
$1 = "SCDH\377"