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

(C언어) write: 파일에 데이터를 쓴다

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

write 함수는 handle로 지시하는 파일에 buf의 내용을 len 길이만큼 저장합니다.

write가 한 번에 기록할 수 있는 바이트 수는 65,535 크기이며, 실제로 기록된 바이트 수가 지정한 갯수보다 작으면 오류로 간주됩니다 - 디크스 오류로 인해 이러한 오류가 발생할 수 있습니다.

 

반환값

기록된 바이트 개수를 반환합니다.

오류가 발생한 경우에는 -1을 반환하고, 전역변수 errno에 다음 중 하나로 설정됩니다.

  • EACCES : 작업이 거절되었다.
  • EBADF : 파일 번호(핸들)가 잘못 되었다.

참고: open, read, write, _open, _read, _write

 

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

int main()
{
	int handle;
	char s[] = "abcdefghijk";
	handle = open("write.txt", O_WRONLY | O_CREAT | O_TEXT | O_TRUNC);
	// handle = open("write.txt", O_CREAT|O_RDWR|O_TRUNC, 0666);  // 파일 모드를 666으로 생성
	if (handle == -1)
	{
		perror("Error: ");
		return 1;
	}

	write(handle, s, strlen(s));

	close(handle);
	
	return 0;
}

write: 파일에 데이터를 쓴다

 

비주얼스튜디어에서는 _write 함수를 사용해야 합니다.

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

int main()
{
	int handle;
	char s[] = "abcdefghijk";
	handle = _open("write.txt", O_WRONLY | O_CREAT | O_TEXT | O_TRUNC);
	if (handle == -1)
	{
		perror("Error: ");
		return 1;
	}

	_write(handle, s, strlen(s));

	_close(handle);
	
	return 0;
}
728x90
반응형