如何fwrite指针的指针?
How to fwrite to pointer of pointer?
我有一个函数应该将 file
的内容存储到指针的指针 - content
。当我尝试检查 fwrite
函数的结果时 - 它 returns 与 writn
无关。我在这里做错了什么?我是否正确分配了内存(如果我想复制整个文件)?
bool load(FILE* file, BYTE** content, size_t* length)
{
int len = 0, writn = 0;
fseek(file, 0, SEEK_END);
*length = len = ftell(file);
rewind(file);
*content = (char) malloc((len + 1) * sizeof(char)); //(len + 1) * sizeof(char)
writn = fwrite(*content, len + 1, 1, file);
return true;
}
您可能以 "r"
模式打开文件,fwrite()
将写入文件,而不是读取。如果是这种情况fwrite()
当然会失败。
也许你只是需要
// Use long int for `length' to avoid a problem with `ftell()'
// read the documentation
bool load(FILE* file, BYTE **content, long int *length)
{
fseek(file, 0, SEEK_END);
*length = ftell(file);
rewind(file);
if (*length == -1)
return false;
*content = malloc(*length + 1);
if (*content == NULL)
return false;
if (fread(*content, 1, *length, file) != *length) {
free(*content);
*content = NULL;
return false;
}
(*content)[*length] = '[=10=]';
return true;
}
您也尝试“读取”比可用数据更多的数据,因为您获得了文件长度并且仍然尝试读取 1 个字节。
我看到这个函数的作用是:
确定文件大小;
分配该大小的内存块;
将该块写入文件。
这假定 file
已打开进行读写。 fseek
查找文件末尾(读取操作);在 rewind
之后写入块(写操作)。如果文件只是为了写入而打开,那么 fseek
可能会失败,因此您的大小将为零。如果文件只是为了阅读而打开,那么您的 fwrite
将失败。另外,tou将未初始化的数据写入文件(分配的内存还没有初始化)。
这是它应该做的吗?
我有一个函数应该将 file
的内容存储到指针的指针 - content
。当我尝试检查 fwrite
函数的结果时 - 它 returns 与 writn
无关。我在这里做错了什么?我是否正确分配了内存(如果我想复制整个文件)?
bool load(FILE* file, BYTE** content, size_t* length)
{
int len = 0, writn = 0;
fseek(file, 0, SEEK_END);
*length = len = ftell(file);
rewind(file);
*content = (char) malloc((len + 1) * sizeof(char)); //(len + 1) * sizeof(char)
writn = fwrite(*content, len + 1, 1, file);
return true;
}
您可能以 "r"
模式打开文件,fwrite()
将写入文件,而不是读取。如果是这种情况fwrite()
当然会失败。
也许你只是需要
// Use long int for `length' to avoid a problem with `ftell()'
// read the documentation
bool load(FILE* file, BYTE **content, long int *length)
{
fseek(file, 0, SEEK_END);
*length = ftell(file);
rewind(file);
if (*length == -1)
return false;
*content = malloc(*length + 1);
if (*content == NULL)
return false;
if (fread(*content, 1, *length, file) != *length) {
free(*content);
*content = NULL;
return false;
}
(*content)[*length] = '[=10=]';
return true;
}
您也尝试“读取”比可用数据更多的数据,因为您获得了文件长度并且仍然尝试读取 1 个字节。
我看到这个函数的作用是:
确定文件大小;
分配该大小的内存块;
将该块写入文件。
这假定 file
已打开进行读写。 fseek
查找文件末尾(读取操作);在 rewind
之后写入块(写操作)。如果文件只是为了写入而打开,那么 fseek
可能会失败,因此您的大小将为零。如果文件只是为了阅读而打开,那么您的 fwrite
将失败。另外,tou将未初始化的数据写入文件(分配的内存还没有初始化)。
这是它应该做的吗?