![](/img/trans.png)
[英]Is it possible to read in a string of unknown size in C, without having to put it in a pre-allocated fixed length buffer?
[英]Copying unknown length buffer to a fixed size buffer in C
我们如何将未知大小的缓冲区复制到c中的固定缓冲区中?
对于我的功能之一,我正在尝试将未知大小的缓冲区复制到固定缓冲区(大小为1024字节)中。 固定大小的缓冲区在结构中声明(稍后,我将需要一次发送该结构的所有内容)。 我不确定哪个功能最能解决此问题。
我将发送结构缓冲区(ex_buffer)并重置结构缓冲区(ex_buffer)中的值; 然后,我需要将未知大小的缓冲区(缓冲区)中的下一个1024个字节存储到固定缓冲区(ex_buffer)中,依此类推。
为了示例目的,我附上了一小段通用代码。
struct example {
char ex_buffer[1024];
}
int main (int argv, char *argv[]){
char *buffer = realloc(NULL, sizeof(char)*1024);
FILE *example = fopen(file,"r");
fseek(example, 0L, SEEK_END);
//we compute the size of the file and stores it in a variable called "ex_size"
fread(buffer, sizeof(char), ex_size, example);
fclose(example);
//Now we want to copy the 1024 bytes from the buffer (buffer) into the struct buffer (ex_buffer)
While( "some counter" < "# of bytes read"){
//copy the 1024 bytes into struct buffer
//Do something with the struct buffer, clear it
//Move onto the next 1024 bytes in the buffer (ex_buffer)
//Increment the counter
}
}
使用memcpy()
,像这样
memcpy(example.ex_buffer, buffer, 1024);
realloc(NULL ...
您实际上应该写malloc()
代替。 sizeof(char)
根据定义为1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.