#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#define NSTRING 5
#define STRSIZE 3
char *string[] = { "aaa", "bbb", "ccc", "ddd", "eee" };
int main(int argc, char **argv) {
int n, fd;
char *fname;
char buf[STRSIZE], answer[8], template[32];
strcpy(template, "/tmp/seekerXXXXXX");
fname = mktemp(template);
fd = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0666);
printf ("debug) file name is %s\n", fname);
for (n = 0 ; n < NSTRING ; n++) {
write(fd, string[n], STRSIZE);
}
for ( ; ; ) {
write(1, "which string ? ", 15);
n = read(0, answer, sizeof(answer));
answer[n-1] = '\0';
n = atoi(answer);
printf ("debug) n is %d\n", n);
printf ("debug) fd is %d\n", fd);
if (n == 0) {
close(fd);
return -1;
}
if (n < 0 || n > NSTRING) {
write (2, "out of range\n", 13);
continue;
}
lseek (fd, (n-1) *STRSIZE, SEEK_SET);
read (fd, buf, STRSIZE);
write(1, "String", 7);
write(1, answer, strlen(answer));
write(1, " = ", 3);
write(1, buf, STRSIZE);
write(1, "\n\n", 2);
}
return 0;
}
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#define NSTRING 5
#define STRSIZE 3
char *string[] = { "aaa", "bbb", "ccc", "ddd", "eee" };
int main(int argc, char **argv) {
int n, fd;
char *fname;
char buf[STRSIZE], answer[8], template[32];
strcpy(template, "/tmp/seekerXXXXXX");
fname = mktemp(template);
fd = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0666);
printf ("debug) file name is %s\n", fname);
for (n = 0 ; n < NSTRING ; n++) {
write(fd, string[n], STRSIZE);
}
for ( ; ; ) {
write(1, "which string ? ", 15);
n = read(0, answer, sizeof(answer));
answer[n-1] = '\0';
n = atoi(answer);
printf ("debug) n is %d\n", n);
printf ("debug) fd is %d\n", fd);
if (n == 0) {
close(fd);
return -1;
}
if (n < 0 || n > NSTRING) {
write (2, "out of range\n", 13);
continue;
}
lseek (fd, (n-1) *STRSIZE, SEEK_SET);
read (fd, buf, STRSIZE);
write(1, "String", 7);
write(1, answer, strlen(answer));
write(1, " = ", 3);
write(1, buf, STRSIZE);
write(1, "\n\n", 2);
}
return 0;
}
read/write/lseek system call을 사용한 예제이다.
fd의 0은 stdin, 1은 stdout, 2는 stderr를 의미. 예약된 번호이다.
'c or linux' 카테고리의 다른 글
stat 파일 상태 확인 (0) | 2010.10.19 |
---|---|
FILE 관련 API (0) | 2010.10.19 |
[리눅스] man (매뉴얼) (0) | 2010.10.18 |
Vxworks 분위기 (0) | 2010.10.18 |
[리눅스] ar, ranlib, ldd, nm, make (0) | 2010.10.18 |