struct member size和exc_bad_access错误

时间:2016-09-30 08:03:03

标签: c struct exc-bad-access

我正在尝试在以下代码中读取struct成员。但是,我要么在循环中的printf语句中获取exc_bad_access,要么strcat复制缓冲区。不知道为什么,我相信我的结构大小正确。问题可能出在终结者char?

有更简单的方法吗?似乎很难确定变量所需的确切大小。

const char *filename = "filetoopen.txt";
FILE *f = fopen(filename, "rb");

if (!f){
    printf("Unable to open file! %s", filename);
    return;
}

char ch;
int counter = 0;
int totalSize,structSize;
int offset = offsetof(struct StructData, data.content);

//length of file
fseek(f, 0L, SEEK_END);
totalSize = ftell(f);

//length of struct in file
fseek(f, offset, SEEK_SET);
structSize = totalSize - ftell(f) ;

char buffer[structSize];

buffer[0] = '\0';
char *store = buffer;

while (counter <= structSize)
{
    fread(&ch, 1, 1, f);
    store += sprintf(store, "%02X", (ch & 0x00FF));
    counter++;
}
strcat(buffer, store);

printf("%s\n", buffer);

fclose(f);

0 个答案:

没有答案