[C++ 언어-막코딩] 15장 파일 입출력
[C++ 언어-막코딩] 15장 파일 입출력
- 다운 사이트 : https://sourceforge.net/projects/orwelldevcpp/
- 웹컴파일러 : https://www.tutorialspoint.com/compile_c_online.php
- 참조 : [C언어-막코딩] 27장 파일 입출력
C++ 에서의 파일 입출력은 코딩이 C보다 간단합니다. 오늘은 C++ 에서 파일 처리를 알아보도록 하죠.
1. fstream 파일
fstream.h 에는 3개의 클래스가 있습니다.
class ifstream : public fstreambase, public istream { //파일읽기
}
class ofstream : public fstreambase, public ostream { //파일쓰기
}
class fstream : public fstreambase, public iostream {
}
여기서 ifstream, ofstream을 이용하여 파일 입출력을 하게 됩니다.
- 파일 읽기 : ifstream 객체명("파일경로");
- 파일 쓰기 : ofstream 객체명("파일경로");
이렇게 딱 두 표현으로 파일을 읽기모드와 쓰기모드로 선언을 하게 됩니다.
2. 파일 입출력
[파일 읽기]
ifstream input("test.txt"); //읽기파일 열기
while(!input.eof()){ //파일 끝인지 체크
getline(input,str); //string str로 파일에 라인데이터 읽기
cout<<str<<endl;
}
input.close(); //파일닫기
[파일 쓰기]
ofstream output("test.txt"); //쓰기 파일 열기
output<<"Hello World!"<<endl; //파일에 쓰기
output.close(); //파일닫기
읽기와 쓰기가 단순해서 C++은 코딩하기가 편합니다.
3. 코딩
test 파일을 하나 만들어서 그곳에 데이터를 쓰고 난 뒤에 만들어진 파일을 다시 읽어와서 확인하는 작업을 코딩하도록 하겠습니다. 정상적으로 데이터를 파일에 쓰고 그 데이터를 읽어 올 수 있는지의 코딩입니다.
[전체소스]
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
string str;
ofstream output("test.txt");
output<<"Hello World!"<<endl;
output<<"Hello SteemIt!"<<endl;
output.close();
ifstream input("test.txt");
while(!input.eof()){
getline(input,str);
cout<<str<<endl;
}
input.close();
return 0;
}
getline(input,str);
string 문자열 변수의 경우는 위와 같이 표현으로 코딩하지만 char [] 문자열의 경우는 이 방법으로 표현합니다.
char str[100];
input.getline(str,100);
이렇게 첫번째 인자는 저장할 문자 배열변수이고 두번째 인자는 읽어올 최대 크기를 지정합니다. 둘 중 편한 방식을 선택하면 됩니다.
cstring 경우는 string.h 파일을 선언해야 문자열 객체를 사용 할 수 있습니다. 빼먹지 마세요.
[결과]
마무리
오늘은 무지 간단한 파일 처리 방법을 다뤘습니다. 처음에는 이렇게 파일을 쓰고 읽는 방법을 다양한 형태로 실습하시고 나서 나중에 파일 처리 관련 자료를 구글 검색을 통해서 좀 더 전문적인 코딩을 연습하세요. 입문자에게는 이정도 파일 처리 코딩 능력만 있어도 충분합니다.
Thank you for your continued support towards JJM. For each 1000 JJM you are holding, you can get an additional 1% of upvote. 10,000JJM would give you a 11% daily voting from the 600K SP virus707 account.
Thank you