截取、拼接字符串,memcpy

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",rc,WEXITSTATUS(rc));
	}

	return 0;
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐