해바

Lab #2 본문

System Programming

Lab #2

Bacha 2019. 11. 16. 21:17

lseek() 시스템 호출을 사용하여, 파일의 원하는 부분을 출력하도록 만든다 :

  • 테스트용 입력파일 "test.txt"에 "abcdefghijklmnop"를 저장한다.
  • lseek 를 사용하여 파일의 시작에서 10개의 character를 건너뛴 후 부터의 내용을 출력한다.
  • lseek 를 사용하여 파일의 끝에서 앞쪽으로 5개의 character를 건너뛴 후 그 내용을 출력한다.

  • 자기 홈 디렉토리에 lab2 디렉토리를 만든 후 프로그램 파일 size.c를 보관할 것

 

 

#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <error.h>
#include <stdio.h>

#define BUFSIZE 512

int main() {
	int fd;
	char buf1[BUFSIZE] = "";
	char buf2[BUFSIZE] = "";

	if ((fd = open("test.txt", O_RDONLY)) == -1) {
		perror("File cannot be opened.");
	}

	if(lseek(fd, 10, SEEK_SET) == -1)  // 파일 시작에서 10개를 건너뛴 후 내용들 출력
		perror("lseek 1");
	read(fd, buf1, BUFSIZE);
	printf("%s\n", buf1);
	
    if(lseek(fd, -5, SEEK_END) == -1)   // 파일 끝에서 5개를 건너뛴 후 그 내용을 출력
        perror("lseek 2");
    read(fd, buf2, BUFSIZE);
	printf("%s\n", buf2);

	close(fd);

	return 0;
}

 

 

컴파일 :

gcc size.c

 

실행 :

./a.out

'System Programming' 카테고리의 다른 글

Lab #6  (0) 2019.11.16
Lab #5  (0) 2019.11.16
Lab #4  (0) 2019.11.16
Lab #3  (0) 2019.11.16
Lab #1  (0) 2019.11.16
Comments