모두의 코드
C++ 레퍼런스 - istream::read 함수
작성일 : 2019-04-19
이 글은 17390 번 읽혔습니다.
istream::read
<istream> 에 정의됨
basic_istream& read(char_type* s, std::streamsize count);
스트림에서 문자들을 받아온다.
이 함수는 sentry 객체를 먼저 생성한 후, 이를 확인한 다음에 s
가 가리키는 공간에 문자들을 읽어와서 저장합니다. 이 떄 아래 조건을 만족할 때 까지 문자들을 계속 읽어들이게 됩니다.
count 개의 문자들을 읽었을 때
EOF 가 발생하였을 때 (이 경우
setstate(failbit|eofbit)
이 호출되었을 것입니다.) 읽어들인 문자의 수는gcount()
함수를 호출함으로써 알아낼 수 있습니다.
인자들
s
- 읽어들인 문자들을 저장할 문자 배열count - 문자 몇 개를 읽을 것인지.
리턴값
*this
실행 예제
#include <cstdint> #include <fstream> #include <iostream> #include <sstream> #include <string> int main() { // read() 는 주로 이진 I/O 에서 사용된다. std::string bin = {'\x12', '\x12', '\x12', '\x12'}; std::istringstream raw(bin); std::uint32_t n; if (raw.read(reinterpret_cast<char*>(&n), sizeof n)) std::cout << std::hex << std::showbase << n << '\n'; std::ofstream("test.txt", std::ios::binary) << "abcd1\nabcd2\nabcd3"; // 문자열에 전체 파일을 읽어서 저장한다. if (std::ifstream is{"test.txt", std::ios::binary | std::ios::ate}) { auto size = is.tellg(); std::string str(size, '\0'); // construct string to stream size is.seekg(0); if (is.read(&str[0], size)) std::cout << str << '\n'; } }
실행 결과
0x12121212 abcd1 abcd2 abcd3
참고 자료
write
: 문자열들을 쓴다.operator>>
: 문자열들을 추출한다.readsome
: 준비된 문자열 블록을 읽는다.get : 문자들을 읽는다.
getline : 주어진 문자가 나올 때 까지 문자들을 읽는다.
fread : 파일에서 읽는다.
첫
댓글을 달아주세요!

강좌에 관련 없이 궁금한 내용은
여기를 사용해주세요
또는 직접 입력하세요 (댓글 수정시 비밀번호가 필요합니다)
댓글을 불러오는 중입니다..