C++/C-String操作/打印log/执行Shell命令

C、C++字符串操作:

C:

  • 在命令行获取用户的输入
  • char * strstr(str_a, str_b, 可选参数),看a字符串里是否有b字符串,如果有返回找到的首位置,如果没有返回0(或者空指针-此处待验证)
  • int strcmp(str_a, str_b)字符串比较,相等是1
  • 分配字符串空间
/*
 * 已经验证,该段程序可用于执行命令中,停下来等待用户输入来作为参数
 * 已经在openpts上验证
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>

 char *test = NULL; //赋值NULL是为了让变量干净些
 test = (char *) malloc(20); //因为前面给的是NULL,必须要先分配空间
// 这里malloc分配的是20个字节,如果是int类型就需要看分配了几个空间了
// 所以为了避免麻烦,可以直接使用"sizeof(类型) * 分配的个数",可读性更好
 scanf("%s", test); //注意这里是传给test,不要传给&test
 printf("test context:\n");
 printf("%s", test);
 free(test); //这里记得释放

C++:

  • 拼接字符串 concatenate string
/*    if (isMatched)
    {
        char a = imgFinal.at<char>(20, 90);

        std::stringstream fmt;
        fmt << a;
        std::string name = "/share/" + fmt.str() + ".jpg";
        cv::imwrite(name, imgFinal);
    }
*/

打印调试信息

C:

#include<stdio></stdio>

FILE *fp_t;
const char c_endl = '\n';
if ((fp_t = fopen("/tmp/test", "w+")) != NULL) // Write to the /tmp/test.
{
	fprintf(fp_t, "%s", scon);
	fprintf(fp_t, "%c", c_endl);
	fprintf(fp_t, "%s", tcon);
	fprintf(fp_t, "%c", c_endl);
	fclose(fp_t);
}

Get Shell-command exec result

C:

int get_command_ret(const char *command, char * ret_p) 
{
    FILE* fp = NULL;
    char res_buf[30];
    fp = popen(command , "r");
    if (fp)
    {
        if (NULL != fgets(res_buf, sizeof(res_buf), fp))
        {
            ret_p = res_buf;
        }
        else
        {
            ret_p = NULL;
        }
    }
    else
    {
        ret_p = NULL;
    }
    pclose(fp);
    return 0;
}
posted @ 2021-11-19 15:42  sparkFY  阅读(101)  评论(0编辑  收藏  举报