본문 바로가기
c

[C] write하고 read하면 결과가 제대로 안 나온다?

by ohojee 2023. 2. 28.
int main(){
	int fd;
	char *buf;
	char str[5] = "hello";
	fd = open("abc.txt", O_RDWR);

	printf("fd: %d \n", fd);
	int j = write(fd, str, 5);
	printf("write return : %d\n", j);
	int i = read(fd, buf, 5);
	printf("read return: %d %s\n",i,buf);
	exit(0);
}

왜 write하고 read하면 write는 fd에 잘 들어가는데 read는 하지 못하는가,,,

 

❗️❗️❗️❗️❗️❗️❗️

write한 후 fd를 닫지 않으면 fd는 open된 상태이기 때문에 EOF 조건에 충족하지 않았다고 판단(어? 파일 열려있는데 아직 쓰고 있을지도 몰라!)하고 계속 읽게 된다
그러면 read를 멈추지 않고 계속 읽게 된다
=> write 후 다 썼다면 fd를 닫아주어야 함!

int main(){
	int fd;
	char *buf;
	char str[5] = "hello";
	fd = open("abc.txt", O_RDWR);

	printf("fd: %d \n", fd);
	int j = write(fd, str, 5);
	printf("write return : %d\n", j);
    close(fd);
	fd = open("abc.txt", O_RDWR);
	int i = read(fd, buf, 5);
	printf("read return: %d %s\n",i,buf);
	exit(0);
}

이렇게 닫고 다시 열어주면 

올바르게 출력이 된다!

 

 

참고 블로그

https://velog.io/@suseodd/Pipe%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80

'c' 카테고리의 다른 글

[c] 메모리 누수(memory leak)/다른 에러들 점검 방법  (0) 2023.02.19
[c] 메모리 구조  (1) 2023.02.19
[C] free할 때 주의할 점  (0) 2022.12.28
[C / 에러] expression result unused  (0) 2022.12.10
[C/에러] Bus error(이중포인터)  (0) 2022.12.10

댓글