gpt4 book ai didi

c - 在 C 中以 block 的形式将内存写入套接字

转载 作者:太空狗 更新时间:2023-10-29 15:39:42 26 4
gpt4 key购买 nike

我正在尝试将内存内容分块写入套接字。我可以写入比我的缓冲区小的文件,但其他任何东西都让我陷入困境。

/* allocate memory for file contents */
char fileContents = malloc(sizeof(char)*filesize);

/* read a file into memory */
read(fileDescriptor, fileContents , filesize);

int chunksWritten;

/* Write the memory to socket? */
if (filesize > MAX_BLOCK_SIZE){

while (chunksWritten < filesize){
// what goes here?
}

} else {
chunksWritten = writen(sd, fileContents, filesize); // this works for files < MAX_BLOCK_SIZE
}

在这里写入我的套接字:

int writen(int fd, char *buf, int nbytes) {
short data_size = nbytes;
int n, nw;
if (nbytes > MAX_BLOCK_SIZE)
return (-3);

data_size = htons(data_size);
if (write(fd, (char *) & data_size, 1) != 1) return (-1);
if (write(fd, (char *) (&data_size) + 1, 1) != 1) return (-1);
/* send nbytes */
for (n = 0; n < nbytes; n += nw) {
if ((nw = write(fd, buf + n, nbytes - n)) <= 0)
return (nw);
}
return (n);
}

这看起来应该很容易,但我正在努力寻找任何好的例子。

最佳答案

/* outside the loop */
chunksWritten = 0;
int smaller;
int r;
int sizeRemaining = filesize;
//char *fileChunk = malloc(sizeof(char)*MAX_BLOCK_SIZE+1);
//memcpy(fileChunk, fileContents, sizeof(char)*MAX_BLOCK_SIZE);
//r = writen(sd, fileChunk, MAX_BLOCK_SIZE);
r = writen(sd, fileContents, MAX_BLOCK_SIZE);
if(r==-1) {
/* deal with error in a manner that fits the rest of your program */
}
chunksWritten = chunksWritten + r;
sizeRemaining = sizeRemaining - MAX_BLOCK_SIZE;

while(sizeRemaining > 0){
if(sizeRemaining > MAX_BLOCK_SIZE){
smaller = MAX_BLOCK_SIZE;
} else {
smaller = sizeRemaining;
}
//memcpy(fileChunk, fileContents+sizeof(char)*chunksWritten, sizeof(char)*smaller);
//r = writen(sd, fileChunk, MAX_BLOCK_SIZE);
r = writen(sd, fileContents[filesize - sizeRemaining], smaller);
if(r==-1) {
/* deal with error in a manner that fits the rest of your program */
}
sizeRemaining = sizeRemaining - MAX_BLOCK_SIZE;
}

/*
Reminder: clean-up fileChunk & fileContents if you don't need them later on
*/

您当然可以修改循环以向上计数而不是向下计数。我可以更好地思考倒数。

编辑:根据评论做了一些修改。

关于c - 在 C 中以 block 的形式将内存写入套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1628587/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com