1.基本信息
strncpy
定义于头文件
<cstring>
函数形式
char* strcpy( char* dest, const char* src );
功能
复制 src 所指向的字符串,包含空终止符,到首元素为 dest 所指向的字符数组。
若 dest 数组不够大则行为未定义。若字符串重叠则行为未定义。
参数
dest - 指向要写入的字符数组的指针
src - 指向复制来源的空终止字节字符串的指针
返回值
deststrncpy
定义于头文件
<cstring>
函数形式
char *strncpy( char *dest, const char *src, std::size_t count );
功能
复制 src 所指向的字节字符串的至多 count 个字符(包含终止空字符)到 dest 所指向的字符数组。
若在复制整个字符串 src 前抵达 count ,则产生的字符数组不是空终止的。
若在复制来自 src 的终止空字符后未抵达 count ,则写入额外的空字符到 dest ,直至写入总共 count 个字符。
若字符串重叠,则行为未定义。
参数
dest - 指向要复制到的字符数组的指针
src - 指向作为复制来源的字节字符串的指针
count - 要复制的最大字符数
返回值
dest
2.代码案例
文件名:strncpy_lib.cpp
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
cout << "hello strncpy() and strcpy()" << endl;
const char* str_tmp1 = "We is having a lunch!";
const char* str_tmp2 = "....";
char char_tmp[50] = {0};
char * pchar = (char*)char_tmp;
if(50 > strlen(str_tmp1))
{
cout << " 50 > " << strlen(str_tmp1) << endl;
cout << "strcpy: " << strcpy(char_tmp, str_tmp1) << endl;
cout << "char_tmp: " << char_tmp << endl;
cout << "strncpy:" << strncpy(char_tmp, str_tmp2, 6) << endl;
cout << "char_tmp: " << char_tmp << endl;
for(int i = 0; i < 50; i++)
{
if(*pchar)
{
cout << *pchar;
}
else
{
cout << "0";
}
pchar++;
}
cout << endl;
}
}
3. Makefile
TGT := app
OPTION := -I.
SRC = strncpy_lib.cpp
all:$(TGT)
@echo "Make successfull!"
$(TGT):$(SRC)
g++ -std=c++11 $(OPTION) $^ -o $@
clean:
ifneq ( ,$(wildcard *.o))
@rm *.o
endif
ifneq ( ,$(wildcard ${TGT}))
@rm $(TGT)
else
@echo "no fie exist, nothing to do"
endif
.PHONY: all clean
4.运行结果
xuehy@ubuntu:/mnt/hgfs/code/lib_study/lib_cpp_and_c$ make
g++ -std=c++11 -I. strncpy_lib.cpp -o app
Make successfull!
xuehy@ubuntu:/mnt/hgfs/code/lib_study/lib_cpp_and_c$ ./app
hello strncpy() and strcpy()
50 > 21
strcpy: We is having a lunch!
char_tmp: We is having a lunch!
strncpy:....
char_tmp: ....
....00having a lunch!00000000000000000000000000000