void getCmdResult(const char* cmd, char** resultbuf, size_t* bufsize) { FILE* fp = popen(cmd, "r"); if (fp) { *resultbuf = malloc(*bufsize); fgets(*resultbuf, *bufsize, fp); pclose(fp); } } HUAYI_BOOL TcpObtainServervalue(int count, ...) { char* resultbuf = NULL; size_t bufsize = 1024; char cmd[TEMP_STR_LEN]; int counter = 0; va_list args; va_start(args, count); strcpy(cmd, "cat /tmp/returnValue"); do { if (counter > 10) return HUAYI_FALSE; else if (counter) sleep(1); if (resultbuf) free(resultbuf); getCmdResult(cmd, &resultbuf, &bufsize); counter++; } while (!strlen(resultbuf)); char* token = strtok(resultbuf, " "); int i = 0; while (token != NULL && i < count) { char* str = va_arg(args, char*); strcpy(str, token); token = strtok(NULL, " "); i++; } va_end(args); unlink("/tmp/returnValue"); free(resultbuf); return HUAYI_TRUE; } char name1[128]; char name2[128]; char name3[128]; TcpObtainServervalue(3,name1,name2,name3); printf("%s,%s,%s",name1,name2,name3);strtok分割不确定是空格分割还是换行分割
时间: 2024-04-09 18:33:06 浏览: 84
在你的代码中,`strtok` 函数使用空格作为分隔符来分割字符串。所以在这种情况下,`strtok` 会将 `resultbuf` 字符串按照空格进行分割。
然而,你可能需要注意的是,`fgets` 函数读取的内容会包含换行符。所以如果 `resultbuf` 字符串以换行符结尾,那么 `strtok` 在分割时会将换行符也作为分隔符,导致分割结果不符合预期。
如果你希望在 `strtok` 中同时支持空格和换行符作为分割符,你可以修改代码如下:
```c
char* token = strtok(resultbuf, " \n"); // 使用空格和换行符作为分隔符
```
这样,`strtok` 就会按照空格和换行符进行分割。
阅读全文