헤더 파일 : string.h
#include <string.h>
void* memcpy(void* destination, const void* source, size_t num);
strcpy와 memcpy 모두 문자열을 복사하는 데 사용된다.
strcpy는 char 하나하나 복사를 하게되고
memcpy는 이름처럼 memory 관점에서 복사이다.
memory 단위로 복사하기 때문에 memory 크기를 넣어주어야 한다.
strcpy는 NULL 체크를 하게 되는데 이러한 차이로 인해 memcpy보다 약간 느리게 된다.
(NULL을 만나면 복사를 중단하기 때문에 char 하나하나 NULL인지 비교한다)
검색해보니 memcpy의 num 인자에 strlen(source)를 넣는 사람도 있던데
그냥 sizeof(destination) 해주면 된다.
물론 destination 크기 >= source의 크기가 되어야 할 것이다.
아, 그리고 memcpy를 하고 난 뒤에 memset()을 써주도록 한다.
예시
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char *name[] = {
"David Hutchison",
"Takeo Kanade",
"Josef Kittler",
"John M. Kleinberg",
"Friedemann Mattern",
"John C. Mitchell",
"Moni Naor",
"Oscar Nierstrasz",
"C. Pandu Rangan",
"Bernhard Steffern",
"Madhu Sudan",
"Demetri Tygar",
NULL
};
int main() {
int i, out;
char wbuf[64];
memset(wbuf, 0, sizeof(wbuf));
if ((out = open("residents", O_CREAT|O_RDWR, 0644)) < 0) {
perror("no testdata");
exit(1);
}
for (i=0; name[i] != NULL; i++) {
memcpy(wbuf, name[i], sizeof(wbuf));
write(out, wbuf, strlen(wbuf));
printf(" %s %d %s\n", wbuf, i+1, name[i]);
memset(wbuf, 0, sizeof(wbuf));
}
close (out);
}
728x90
반응형
'Unix' 카테고리의 다른 글
저수준 파일 입출력 (read, write) (1) | 2022.09.21 |
---|---|
저수준 파일 입출력 (open, close) (2) | 2022.09.20 |