[英]Looping in a fwrite call until the buffer size is written C/C++
I'm designing a C++
callback function that writes size_t size
bytes from a buffer to a file in C++. 我正在设计一个C++
回调函数,它将size_t size
字节从缓冲区写入C ++中的文件。 However, for sanity, I have to check if fwrite
returns a errno
such as EACESS
. 但是,为了理智,我必须检查fwrite
返回errno
例如EACESS
。 The function itself it's an interface between C
and C++
. 函数本身是C
和C++
之间的接口。 Sure enough, I have a pseudocode (almost real code) written: 果然,我写了一个伪代码(几乎是真正的代码):
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream){
int nwritten = size;
while(nwritten > 0){
int written = fwrite(ptr, size, nmemb, (FILE*)stream);
if(written < 0 && errno == EACESS){
// try again
written = 0;
}
/* check some other errors which may be recoverable
nwritten -= written;
}
The function itself is called from libcurl : 函数本身是从libcurl调用的:
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
The point is to make sure size_t written = size
bytes were written to the file. 关键是要确保将size_t written = size
字节写入文件。 The reason I'm using a fwrite
instead any other method is because the function write_data
is passed as a callback to a method which does a HTTP
request, makes some file transfering and writes the file content to a local file. 我使用fwrite
而不是任何其他方法的原因是因为函数write_data
作为回调传递给执行HTTP
请求的方法,进行一些文件传输并将文件内容写入本地文件。 I'm not sure this approach will work. 我不确定这种方法是否有效。 Could you guys tell me if this approach would work, or maybe potential troubles I may have? 你能告诉我这种方法是否有效,或者我可能遇到的潜在问题? If there is a better approach ? 如果有更好的方法? Thanks 谢谢
fwrite
returns the number of members written, so as you write members you need to advance ptr
, something like this: fwrite
返回写入的成员数,因此当你编写成员时需要提升ptr
,如下所示:
size_t done = 0;
while (done < nmemb) {
size_t written = fwrite((char*)ptr + done * size, size, nmemb - done, (FILE*)stream);
done += written;
if (done < nmemb) {
/* Not all has been written. Some kind of error may have occurred. */
if (ferror((FILE*)stream)) {
...
}
}
}
I think what you are looking for is a robust i/o. 我认为您正在寻找的是强大的i / o。 This link and the robust io package might help you : http://csapp.cs.cmu.edu/public/ch10-preview.pdf 此链接和强大的io包可能对您有所帮助: http : //csapp.cs.cmu.edu/public/ch10-preview.pdf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.