zl程序教程

您现在的位置是:首页 >  其它

当前栏目

截取、拼接字符串,memcpy

字符串 截取 拼接 memcpy
2023-09-11 14:14:44 时间

1. 截取字符串

#include<string.h>
 
int main(
{
    char* s="GoldenGlobalView";
    char d[20];
    memcpy(d,s+12,4);    //从第13个字符(V)开始复制,连续复制4个字符(View)
    d[4]='\0';           //memcpy(d,s+14*sizeof(char),4*sizeof(char));也可
    printf("%s",d);
    getchar();
    return 0;
}
 
输出结果:
View

2. 填充字符串

/*取得当前目录下的文件个数*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>

#define MAXLINE 1024
#define RES_MAX 10240

int main()
{
	char result_buf[MAXLINE], command[MAXLINE];
	char result[RES_MAX] = {0};
	int rc = 0; // 用于接收命令返回值
	FILE *fp;

	/*将要执行的命令写入buf*/
	snprintf(command, sizeof(command), "ls ./");

	/*执行预先设定的命令,并读出该命令的标准输出*/
	fp = popen(command, "r");
	if(NULL == fp)
	{
		perror("popen执行失败!");
		exit(1);
	}
	while(fgets(result_buf, sizeof(result_buf), fp) != NULL)
	{
		/*为了下面输出好看些,把命令返回的换行符去掉*/
		if('\n' == result_buf[strlen(result_buf)-1])
		{
			result_buf[strlen(result_buf)-1] = '\0';
		}
	//	printf("命令【%s】 输出【%s】\r\n", command, result_buf);
		memcpy(result + strlen(result), result_buf, strlen(result_buf));
		result[strlen(result)] = ',';
	}
	printf ("result = %s\n", result);

	/*等待命令执行完毕并关闭管道及文件指针*/
	rc = pclose(fp);
	if(-1 == rc)
	{
		perror("关闭文件指针失败");
		exit(1);
	}
	else
	{
		printf("命令【%s】子进程结束状态【%d】命令返回值【%d】\r\n", command, rc, WEXITSTATUS(rc));
	}

	return 0;
}