简体   繁体   English

无法将缓冲区的内容复制到字符串中:从C中的.bin文件读取

[英]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. 使用fread可以在缓冲区b中打印每个元素的内容,但是如果我尝试打印整个字符串(b),则不会打印任何内容。 This is done in my code in the for loop; 这是在for循环的代码中完成的; I print the contents of b[i]. 我打印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. 然后在for循环之后,我尝试打印b,然后将b的内容放入我创建的结构中,供其他地方使用。

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 . 您将间接返回指向本地数组b的指针。 It goes out of scope when the function returns and the value stored in P[framenum].content is no longer valid. 当函数返回并且存储在P[framenum].content值不再有效时,它将超出范围。 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. 除了泄漏内存外,目前还不清楚您正在使用temp做什么。 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). 但是,您可以很好地利用它而不是使用b (但是您必须测试对malloc()调用是否成功)。 The calling code would have to free the memory in P[framenum].content when it is finished with. 完成后,调用代码将必须释放P[framenum].content的内存。

You need to capture and use the value returned by fread() . 您需要捕获并使用fread()返回的值。 You need to validate that the file was opened successfully. 您需要验证文件是否成功打开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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