質問

ソケットにメモリの内容をチャンクで書き込もうとしています。私は自分のバッファよりも小さいファイルを書くことができますが、それ以外のものはすべて、私は深海にいます。

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

writenはここでソケットに書き込みます:

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;
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top