C_C++/C_라이브러리_함수

(C언어) read, _read: 파일에서 데이터를 읽는다

고니자니 2023. 3. 14. 11:19
반응형
#include <io.h>
int read(int handle, void *buf, unsigned len);

read 함수는 hanle로 지정된 파일로부터 len 바이트의 문자를 읽어 buf에 저장합니다.

파일이 텍스트 모드로 열려있으면 캐리지 리턴을 제거하며, Ctrl_Z를 만나면 EOF는 반환합니다.

read 함수가 읽어 들일 수 있는 바이트의 최대 크기는 65,534 바이트입니다.

 

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <io.h>

int main()
{
	int handle;
	char s[100] = { 0 };
	handle = open("open.txt", O_RDONLY);
	if (handle == -1)
	{
		perror("Error: ");
		return 1;
	}

	read(handle, s, 100);
	printf("%s\n", s);
	
	close(handle);
	
	return 0;
}

read 함수

 

반응형

 

 

비주얼스튜디오에서는 _open, _read, _close 함수를 사용합니다.

#define _CRT_SECURE_NO_WARNINGS  // Visual Studio
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <io.h>

int main()
{
	int handle;
	char s[100] = { 0 };
	handle = _open("open.txt", O_RDONLY); // O_CREAT | O_TEXT);
	if (handle == -1)
	{
		perror("Error: ");
		return 1;
	}

	_read(handle, s, 100);
	printf("%s\n", s);
	
	_close(handle);
	
	return 0;
}

 

 

728x90
반응형