[C++ 언어-막코딩] 17장 CSV 파일 처리

in #kr-dev6 years ago (edited)

[C++ 언어-막코딩] 17장 CSV 파일 처리



지난 시간에 fstream 파일에는 세개의 클래스가 있다고 했죠. ifstream, ofstream, fstream 클래스가 있습니다. 지난시간에 파일 입출력으로 ifstream(파일읽기), ofstream(파일쓰기)로 연습했는데 마지막 글래서 fstream 클래스 하나로 입출력을 할 수 있습니다. 이 부분을 지난시간에 빼먹어서 오늘 주제로 결정했네요. 그냥 하면 재미 있으니 csv 파일을 읽어와서 출력하는 실습을 해보는 시간을 갖도록 하겠습니다.

1. fstream 클래스


class fstream : public fstreambase, public iostream {
}

위 클래스 내부 함수들은 ifstream과 ofstream에서 쓰던 방식과 크게 차이가 없습니다.

fstream fs; 
fs.open("파일명", ios::in or ios::out);
fs.close();

위 코딩에서 파일명을 지정해주고 in은 해당 위치에 파일이 읽겠다는 의미이고, out은 해당 위치에 파일을 쓰겠다는 의미입니다. 둘중 하나 모드를 지정해주면 파일을 읽을지 쓸지가 결정됩니다. 나머지 사용법은 같습니다.

2. 코딩


  • 실습 : CSV 파일을 읽어와서 콘솔창에서 출력하시오

[test.csv 파일]

a1.jpg

엑셀 파일로 특정 데이터를 만들고 저장을 csv 파일을 만드는데 구분자는 콤마(,)로 해서 데이터 파일을 만듭니다.

이 파일을 읽기 위해서

fstream fs; 
fs.open("test.csv",ios::in);

fs로 읽기모드로 읽어 오면 끝납니다.

읽을 때 지난시간에 쓴 getline()함수를 이용합니다.

getline(파일객체,저장변수,구분자);
getline(fs,str_buf,',');

fs 파일객체에서 읽어오는 콤마(,) 구분자로 해서 읽어오게 됩니다. 실질적으로 str_buf 변수에는 콤마이전까지의 문자열값을 읽어오게 됩니다. 이렇게 해서 콤마를 기준으로 읽어온 데이터를 출력해서 결과를 확인 할까요.

[전체소스]

#include <iostream>
#include <string.h>
#include <fstream>

using namespace std;

int main(int argc, char** argv) {
    
    
    string str_buf;         
    fstream fs; 
    
    fs.open("test.csv",ios::in);
    
    while(!fs.eof()){
        getline(fs,str_buf,',');
        cout<<str_buf<<endl;        
    }
    fs.close();
    
    return 0;
}

[결과]
a2.jpg

콤마를 기준으로 한개씩 읽어오게 됩니다. 이 읽어온 데이터를 어떻게 처리 할지는 여러분의 몫으로 남겨 두겠습니다.

마무리


오늘은 지난 시간에 빼먹은 fstream 클래스 하나로 파일 입출력하는 방법을 알아 보았습니다. 위 실습에서는 읽어오는 실습만 했지만 ios::out 모드로 바꾸고 파일객체에 "fs<<출력데이터"로 표현하여 출력 파일에 데이터를 쓰기만 하면 됩니다. 이건 여러분들이 위 읽기 코딩을 수정하여 쓰기 코딩으로 바꾸는 실습을 직접 해보세요.


Sponsored ( Powered by dclick )

dclick-imagead

Sort:  

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.

Congratulations @codingman! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You published a post every day of the week

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.13
TRX 0.35
JST 0.034
BTC 115061.49
ETH 4517.11
SBD 0.86