Question

I have a char array in a C application that I have to split into parts of 250 so that I can send it along to another application that doesn't accept more at one time.

How would I do that? Platform: win32.

Was it helpful?

Solution

From the MSDN documentation:

The strncpy function copies the initial count characters of strSource to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. If count is greater than the length of strSource, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap.

Note that strncpy doesn't check for valid destination space; that is left to the programmer. Prototype:

char *strncpy( char *strDest, const char *strSource, size_t count );

Extended example:

void send250(char *inMsg, int msgLen)
{
    char block[250];
    while (msgLen > 0)
    {
         int len = (msgLen>250) ? 250 : msgLen;
         strncpy(block, inMsg, 250);

         // send block to other entity

         msgLen -= len;
         inMsg  += len;
    }
}

OTHER TIPS

I can think of something along the lines of the following:

char *somehugearray;
char chunk[251] ={0};
int k;
int l;
for(l=0;;){
  for(k=0; k<250 && somehugearray[l]!=0; k++){
    chunk[k] = somehugearray[l];
    l++;
  }
  chunk[k] = '\0';
  dohandoff(chunk);
}

If you strive for performance and you're allowed to touch the string a bit (i.e. the buffer is not const, no thread safety issues etc.), you could momentarily null-terminate the string at intervals of 250 characters and send it in chunks, directly from the original string:

char *str_end = str + strlen(str);
char *chunk_start = str;

while (true) {
    char *chunk_end = chunk_start + 250;

    if (chunk_end >= str_end) {
        transmit(chunk_start);
        break;
    }

    char hijacked = *chunk_end;
    *chunk_end = '\0';
    transmit(chunk_start);
    *chunk_end = hijacked;

    chunk_start = chunk_end;
}

jvasaks's answer is basically correct, except that he hasn't null terminated 'block'. The code should be this:

void send250(char *inMsg, int msgLen)
{
    char block[250];
    while (msgLen > 0)
    {
         int len = (msgLen>249) ? 249 : msgLen;
         strncpy(block, inMsg, 249);
         block[249] = 0;

         // send block to other entity

         msgLen -= len;
         inMsg  += len;
    }

}

So, now the block is 250 characters including the terminating null. strncpy will null terminate the last block if there are less than 249 characters remaining.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top