How to get n characters from char array

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

How can I do it? Platform: win32.

+4
source share
4 answers

From the MSDN documentation:

The strncpy function copies the leading characters of the strSource account to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not automatically added to the copied string. If the counter is greater than the length of strSource, the target string is filled with null characters to the length. The behavior of strncpy is undefined if the source and target lines overlap.

Note that strncpy does not check the correct destination; which remains 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; } } 
+4
source

I can think of something in the following lines:

 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); } 
+1
source

If you want performance, and you are allowed to touch the line a little (i.e., the buffer is not constant, does not have thread safety problems, etc.), you can instantly reset the line with an interval of 250 characters and send it to pieces directly from the source line:

 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; } 
+1
source
Answer to

jvasaks is basically correct, except that it does not have a complete 'block' character. The code should be as follows:

 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 contains 250 characters, including trailing zero. strncpy will null terminate the last block if less than 249 characters are left.

0
source

Source: https://habr.com/ru/post/1277401/


All Articles