乐闻世界logo
搜索文章和话题

C : correct usage of strtok_r

1个答案

1

In the C programming language, strtok_r is a function used for splitting strings and serves as the thread-safe variant of strtok. This means that strtok_r can be safely used in multi-threaded programs, whereas strtok may cause issues because it relies on static storage to store the remaining string from the previous call.

strtok_r Function Prototype:

c
char *strtok_r(char *str, const char *delim, char **saveptr);
  • str: The original string to be split; in the first call, it points to the string to be split, and in subsequent calls, it must be set to NULL.
  • delim: A string containing delimiters used to split the original string.
  • saveptr: Used to store the position of the remaining string for the next function call.

Usage Example:

Suppose we have a task to split a line of text where words are separated by spaces.

c
#include <stdio.h> #include <string.h> int main() { char input[] = "Hello world this is an example"; char *token; char *rest = input; while ((token = strtok_r(rest, " ", &rest))) { printf("Token: %s\n", token); } return 0; }

In this example:

  1. The input string contains the original text to be split.
  2. We obtain each word (with space as the delimiter) step by step using strtok_r within a while loop.
  3. The first parameter is the string to be split (input) in the initial call; for subsequent calls to retrieve remaining substrings, it is set to NULL.
  4. The delim parameter is a string containing a single space character, representing the delimiter.
  5. The saveptr parameter stores the position of the remaining string during the call for the next invocation.

Important Notes:

  • Use strtok_r instead of strtok in multi-threaded environments to avoid race conditions and other thread-safety issues.
  • After using strtok_r to split the string, the original input string is modified because strtok_r inserts '\0' at each delimiter.

Through this example and explanation, you can see how strtok_r is used in actual programs to safely split strings, especially when thread safety is required.

2024年6月29日 12:07 回复

你的答案