简体   繁体   中英

Cannot copy contents of buffer into string: reading from .bin file in C

I have a function that reads in a certain number of bytes from a file and put those bytes into a string. Using fread I can print the content of each element in my buffer, b, but if I try to print the whole string (b) nothing prints out. This is done in my code in the for loop; I print the contents of b[i]. and then after the for loop I try to print b and later put the contents of b into a structure I've created for use elsewhere.

Any ideas on why this is happening?

void load_frame(struct Entry P[], int framenum){
char b[256];
FILE*fp;
char *temp = malloc(256);
fp = fopen("BACKING_STORE.bin", "rb");

printf("We opened the file\n");
fseek(fp, 256*framenum,SEEK_SET);

fread(b, sizeof(b), 1, fp);

fclose(fp);
int i;
printf("Looking at the contents of buffer: \n");

for(i = 0; i < 10; i ++){
    printf("%u\n", b[i]);   

}
//Print contents of whole buffer
printf("%s",b);
//b[10] = "\0";


//Put b into char* content part of structure Entry
P[framenum].content = b;
printf("Content is: %s\n", P[framenum].content);
P[framenum].frame=framenum;

}

You are indirectly returning a pointer to the local array b . It goes out of scope when the function returns and the value stored in P[framenum].content is no longer valid. It can be overwritten by other functions because it is no longer your memory to use.

Additionally, does the buffer start with a null byte? Does it contain null bytes? These will terminate the string.

It isn't clear what you're doing with temp other than leaking memory. However, you could make good use of it instead of using b (but you'd have to test that your call to malloc() was successful). The calling code would have to free the memory in P[framenum].content when it is finished with.

You need to capture and use the value returned by fread() . You need to validate that the file was opened successfully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM