在C中以块的forms将内存写入套接字

我正在尝试将内存内容写入块中的套接字。 我可以写出比我的缓冲区小的文件,但是其他任何东西,我都在深水中。

/* 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 } 

写在这里写到我的sockets:

 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 */ 

你当然可以重新设计循环来计算而不是减少。 我可以更好地倒计时。

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

不知道为什么你想要这个,但似乎你想要这样的东西:

 #define MIN(x, y) ((x) < (y) ? (x) : (y)) while (chunksWritten < filesize) { int writtenThisPass = writen(fd, fileContents + chunksWritten, MIN(filesize - chunksWritten, MAX_BLOCK_SIZE)); if (writtenThisPass <= 0) { // TODO: handle the error } else { chunksWritten += writtenThisPass; } }