영넌 개발로그
[C++ 기초] text file 읽고 쓰기, fstream 헤더 본문
File
1. binaryfile : (mp3 ...)
2. text file : 노트패드로 열었을 때 사람의 눈으로 알기 쉽게 보이는 파일 (cpp, txt ...)
파일 쓰기
ofstream | output file |
ofstream outFile; | ofstream이 하나의 데이터형 (class) |
outFile.open('text.txt') | 열고 쓰기 |
outFile.close() | 닫아야 제대로 기록이 남아있음 |
예제 실행코드>
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outFile;
outFile.open("yyy.txt");
//사람 이름, 나이, 체중
cout << "Name: ";
char name[50];
cin.getline(name, 50);// 공백이 있을 수도 있어서 line으로 받음
outFile << name << endl;
cout << "Age: ";
unsigned short age; //0~65000
cin >> age;
outFile << age << endl;
cout << "Weight: ";
double weight;
cin >> weight;
outFile << weight << endl;
outFile.close();
return 0;
}
파일 읽기
ifstream | input file |
ifstream inFile; | ifstream이 하나의 데이터형 (class) |
inFile.open('test.txt') | 열고 읽기 |
inFile.is_open() | bool 반환값, 파일을 제대로 열면 true |
inFile.good() | bool 반환값, 아직도 읽을 내용이 있으면 true |
inFile.eof() | bool 반환값, end of file, 파일 끝에 도달하면 true |
inFile.fail() | bool 반환값, 파일 끝이 아닌데 읽기 실패 |
inFIle.close() | 컴퓨터의 자원낭비를 하지 않기 위해 꼭 닫아줌 |
예제 실행코드 1>
파일 내의 내용이 짧아 형식이 어떤지 알고 있을 경우,
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outFile;
ifstream inFile;
inFile.open("yyy.txt");
if (inFile.is_open() == false) {
cout << "Unable to openthe file" << endl;
return -1;
}
char name[50];
unsigned short age;
double weight;
inFile.getline(name, 50);
inFile >> age;
inFile >> weight;
cout << name << "는 " << age << "살이고, " << weight << "kg이다" << endl;
return 0;
}
예제 실행코드 2>
파일 내의 내용이 긴 경우,
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outFile;
ifstream inFile;
inFile.open("numbers.txt");
if (inFile.is_open() == false) {
cout << "Unable to openthe file" << endl;
return -1;
}
int value;
int sum(0);
while (true) {
if (inFile.good() == false) {
break;
}
inFile >> value;
sum += value;
}
if (inFile.eof() == true) {
cout << "Sum is " << sum << endl;
inFile.close();
return 0;
}
else if (inFile.fail() == true) {
cout << "Failure,, file read" << endl;
inFile.close();
return -1;
}
inFile.close();
return 0;
}
'코딩 > C++' 카테고리의 다른 글
[C++ 기초] 참조 변수 Reference variable (0) | 2020.10.26 |
---|---|
[C++ 기초] 함수 파라미터, 아규먼트로 배열 입력(1차원, 다차원) /함수 포인터 Function Pointer (0) | 2020.10.23 |
[C++ 기초] cctype 헤더파일 (0) | 2020.10.23 |
[C++ 기초] 반복문 for loop / 논리 연산자 logical_operator (0) | 2020.10.23 |
Comments