所以我正在从一个文件中读入一个缓冲区。默认情况下,此方法不会 null 终止我的字符串。
size_t result;
size_t total = 0;
/* Get the file size */
FILE* pfile;
pfile = fopen(filename, "rb");
fseek(pfile, 0, SEEK_END);
long lfile = ftell(pfile);
rewind(pfile);
char* file_buffer = malloc(sizeof(char) * lfile);
while ((result = fread(file_buffer, 1, lfile, pfile)) > 0)
{
total += result;
}
resp->content_length = lfile;
file_buffer[lfile] = '\0'; //so I try to null terminate it here.
但是我收到大小为 1 的无效写入。我做错了什么?
是否有另一种方法可以 null 终止缓冲区中的内容?
最佳答案
在调用 malloc
时,您对字符串长度的计算似乎有误。您必须添加 1
以说明 0
字符。
编辑:顺便说一句,您对 sizeof(char)
的使用……毫无用处。 sizeof
和 malloc
只是定义了它们以 char
的大小计数,所以 sizeof(char)
将始终为 1
。
关于c - 将 '\0' 添加到非空终止 "string"的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20387600/