C++I/O 파일 읽 기 쓰기 작업 의 예제 코드
9139 단어 C++I/O 파일읽 기와 쓰기 동작
c++에 서 는 정 의 된 클래스 를 통 해 IO(입 출력)를 처리 해 야 합 니 다.
파일 흐름:파일 읽 기 및 쓰기 작업
헤더 파일:
라 이브 러 리:
ifstream 파일 입력(파일 읽 기)
ofstream 파일 출력(파일 쓰기)
fstream 파일 입력 또는 출력
//파일 쓰기
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int age;
ofstream outfile; // fstream, fstream
// ofstream , ios::out | ios::trunc
// fstream , ios::out
//
outfile.open("user.txt", ios::out | ios::trunc);
while (1) {
cout << " : [ctrl+z ] ";
cin >> name;
if (cin.eof()) { //
break;
}
outfile << name << "\t";
cout << " : ";
cin >> age;
outfile << age << endl; //
}
//
outfile.close();
system("pause");
return 0;
}
//파일 읽 기
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int age;
ifstream infile;
infile.open("user.txt");
while (1) {
infile >> name;
if (infile.eof()) { //
break;
}
cout << name << "\t";
infile >> age;
cout << age << endl;
}
//
infile.close();
system("pause");
return 0;
}
바 이 너 리 파일 스 트림 읽 기 쓰기텍스트 파일 과 바 이 너 리 파일 의 차이 점 은?
텍스트 파일:숫자 1 을 쓰 고 실제 기록 한 것 은'1'입 니 다.
바 이 너 리 파일:숫자 1 을 쓰 고 실제 적 으로 정수 1(4 바이트,최저 바이트 1,높이 3 바이트 모두 0)을 기록 합 니 다.
'R'이 라 고 쓰 여 있어 요.실제로 입력 한 거 예요,'R'이에 요?
바 이 너 리 파일 쓰기
파일 스 트림 대상 의 write 방법 으로 바 이 너 리 데 이 터 를 기록 합 니 다.
//바 이 너 리 파일 쓰기
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int age;
ofstream outfile;
outfile.open("user.dat", ios::out | ios::trunc | ios::binary);
while (1) {
cout << " : [ctrl+z ] ";
cin >> name;
if (cin.eof()) { //
break;
}
outfile << name << "\t";
cout << " : ";
cin >> age;
//outfile << age << endl; //
outfile.write((char*)&age, sizeof(age));
}
//
outfile.close();
system("pause");
return 0;
}
//바 이 너 리 파일 읽 기파일 스 트림 대상 의 read 방법 을 사용 합 니 다.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int age;
ifstream infile;
infile.open("user.dat", ios::in | ios::binary);
while (1) {
infile >> name;
if (infile.eof()) { //
break;
}
cout << name << "\t";
//
char tmp;
infile.read(&tmp, sizeof(tmp));
//infile >> age; // ,
infile.read((char*)&age, sizeof(age));
cout << age << endl; //
}
//
infile.close();
system("pause");
return 0;
}
파일 흐름 에 대해 형식 대로 데 이 터 를 읽 고 쓰기stringstream 사용 하기
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string name;
int age;
ofstream outfile;
outfile.open("user.txt", ios::out | ios::trunc);
while (1) {
cout << " : [ctrl+z ] ";
cin >> name;
if (cin.eof()) { //
break;
}
cout << " : ";
cin >> age;
stringstream s;
s << "name:" << name << "\t\tage:" << age << endl;
outfile << s.str();
}
//
outfile.close();
system("pause");
return 0;
}
지정 한 형식 으로 파일 읽 기우아 한 C++솔 루 션 없 이 C 언어 를 사용 하 는 sscanf
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <Windows.h>
using namespace std;
int main(void)
{
char name[32];
int age;
string line;
ifstream infile;
infile.open("user.txt");
while (1) {
getline(infile, line);
if (infile.eof()) { //
break;
}
sscanf_s(line.c_str(), " :%s :%d", name, sizeof(name),&age);
cout << " :" << name << "\t\t :" << age << endl;
}
infile.close();
system("pause");
return 0;
}
파일 흐름 상태 검사s.is_open( )
파일 흐름 이 열 렸 는 지 여부,
s.eof()흐름 s 종료 여부
s.fail( )
스 트림 의 failbit 또는 badbit 가 설치 되 었 을 때 true 로 돌아 갑 니 다.
failbit:비치 명 적 인 오류 가 발생 하면 만회 할 수 있 습 니 다.일반적으로 소프트웨어 오류 입 니 다.
badbit 위치 설정,치 명 적 인 오류 가 발생 합 니 다.일반적으로 하드웨어 오류 나 시스템 바 텀 오류 입 니 다.돌 이 킬 수 없습니다.
s.bad( )
흐름 s 의 badbit 위치 설정 시 true 로 돌아 갑 니 다.
s.good( )
흐름 s 가 유효 상태 일 때 true 로 돌아 갑 니 다.
s.clear( )
흐름 s 의 모든 상태 가 복원 되 었 습 니 다.
파일 흐름 위치 지정
seekg( off_type offset,//오프셋
ios::seekdir origin ); //시작 위치
역할:입력 흐름 의 위 치 를 설정 합 니 다.
인자 1:오프셋
인자 2:상대 위치
beg 시작 위치 대비
cur 현재 위치 대비
end 끝 위치 대비
현재 프로그램의 마지막 50 자 읽 기
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void) {
ifstream infile;
infile.open(" .cpp");
if (!infile.is_open()) {
return 1;
}
infile.seekg(-50, infile.end);
while (!infile.eof()) {
string line;
getline(infile, line);
cout << line << endl;
}
infile.close();
system("pause");
return 0;
}
//tellg 이 입력 흐름 의 현재 위 치 를 되 돌려 줍 니 다.(파일 의 시작 위치 에서 의 오프셋)현재 파일 의 길이 가 져 오기
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void) {
ifstream infile;
infile.open(" .cpp");
if (!infile.is_open()) {
return 1;
}
//
infile.seekg(0, infile.end);
int len = infile.tellg();
cout << "len:" << len;
infile.close();
system("pause");
return 0;
}
seekp 이 출력 흐름 의 위 치 를 설정 합 니 다.새 파일 에 먼저 쓰기:"123456789"
그리고 네 번 째 문자 위치 에'ABC'를 기록 합 니 다.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void) {
ofstream outfile;
outfile.open("test.txt");
if (!outfile.is_open()) {
return 1;
}
outfile << "123456789";
outfile.seekp(4, outfile.beg);
outfile << "ABC";
outfile.close();
system("pause");
return 0;
}
컴퓨터 영어ioinput output 의 약자
출력
iosC+출력 흐름 의 기본 클래스
스 트림 흐름
istream 입력 흐름
ostream 출력 흐름
iostream 출력 흐름
fstreamfile stream 의 약자 파일 흐름
ifstream 파일 입력 흐름
ofstream 파일 출력 흐름
stringstream 문자 직렬
istringstream 문자열 입력 흐름
ostringstream 문자열 출력 흐름
찾다
seekg 입력 흐름 위치 설정
seekp 출력 흐름 의 위 치 를 설정 합 니 다.
알리다
tellg 현재 흐름 의 위치 로 돌아 가기
열다
is_오픈 성공 여부
eofend of file 의 약자
파일 끝
좋다
나쁘다
실패 실패
흔히 볼 수 있 는 오류 총화
1.파일 이 닫 히 지 않 음
파일 이 닫 히 지 않 았 습 니 다.close()는 파일 을 쓰 는 데 실 패 했 을 수 있 습 니 다.
2.파일 열기 방식 이 적합 하지 않 음
3.VS 2015 일부 버 전에 서 sscanf 와 sscanfs 형식 문자열 에 중국어 가 포함 되 어 있 을 때 읽 기 에 실 패 했 을 수 있 습 니 다.
vs 2019 에서 이러한 문 제 는 발견 되 지 않 았 다.
C++I/O 파일 읽 기와 쓰기 동작 에 관 한 예제 코드 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 관련 C+I/O 파일 읽 기와 쓰기 동작 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 지원 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Visual Studio에서 파일 폴더 구분 (포함 경로 설정)Visual Studio에서 c, cpp, h, hpp 파일을 폴더로 나누고 싶었습니까? 어쩌면 대부분의 사람들이 있다고 생각합니다. 처음에 파일이 만들어지는 장소는 프로젝트 파일 등과 같은 장소에 있기 때문에 파일...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.