create account

[C언어] CSV 데이터 파일을 strtok()함수로 처리 by codingman

View this thread on: hive.blogpeakd.comecency.com
· @codingman · (edited)
$1.98
[C언어] CSV 데이터 파일을 strtok()함수로 처리
# [C언어] CSV 데이터 파일을 strtok()함수로 처리
-----
오늘은 지난 시간에 strtok()함수로 문자열을 쪼개고 그 쪼갠 문자열을 숫자로 변환하여 숫자의 합을 구해 보았습니다. 실제 CSV 파일을 읽어와서 지난 시간의 했던 숫자의 합을 구현해 보는 것이 공부에 도움이 될 것 같다는 생각에 그냥 넘어 가려다가 post로 작성해 봅니다.

## 1. 파일 읽기
-----
```
FILE *pFile = NULL;
pFile = fopen("test.csv", "r" ); //파일 열기
fclose( pFile ); //파일 닫기
```
파일을 읽기 위해서 위와 같은 코딩을 합니다. 딱 세줄이면 파일을 열고 닫을 수 있습니다. pFile에는 읽어 온 파일의 정보가 저장되어 있겠죠. 이 pFile에 저장된 정보를 어떻게 읽은 것인지만 정해서 읽으면 됩니다.

실험에서는 라인으로 읽고 읽는 글자의 범위는 대충 적당한 크기를 정해서 읽을 예정입니다.

그러면 CSV 파일이 정상적으로 읽어오는지 확인해 봅시다.

**[test.csv]**
```
10,20,30
40,50,60
70,80,90
```

**[코딩]**
```
#include <stdio.h>

int main(int argc, char *argv[]) {
	
	char str_tmp[1024];
	FILE *pFile = NULL;

	pFile = fopen("test.csv", "r" );
	if( pFile != NULL )
	{	
		while( !feof( pFile ) ){
			fgets( str_tmp, 1024, pFile );			
			printf( "%s", str_tmp );			
		}		
	}
	fclose( pFile );
	
	return 0;
}
```
fgets()함수로 해서 라인으로 읽어오는데 pFile의 정보에서 최대 1024데이터 크기로  읽어옵니다. str_tmp에는 읽어온 데이터가 저장되게 됩니다. 참고로 반환값은 따로 변수를 선언하면 해당 읽어온 값을 반환값으로 받을 수 있습니다.

```
p = 	fgets( str_tmp, 1024, pFile );			
```
이렇게 하면 읽어온 라인값은 p에 저장됩니다. 사용방법은 코딩하는 분들의 스타일에 맞게 코딩하시면 됩니다.

**[결과]**
![a1.jpg](https://cdn.steemitimages.com/DQmSXSa4gmoDetq5dn7LL9eFY27ZJhcCGkFnGHUhA6Kfen2/a1.jpg)

## 2. CSV 데이터 파일 합 구하기
-----
- [C언어] 문자열 쪼개기(strtok) : https://steemit.com/kr-dev/@codingman/c-strtok-1552953745917

-----
지난 시간 post에 코딩한 소스를 오늘 파일읽기에 그대로 대입하여 실행을 시켜보겠습니다. 외부함수로 해서 별도록 보기 좋게 하려다가 그냥 main()함수 안에다 다 집어 넣었네요. 

**[코딩]**
```
#include <stdio.h>
#include <string.h>


int main(int argc, char *argv[]) {
	
	char str_tmp[1024];
	char *p;
	int b[3] = {0,0,0};
	int cnt, sum, i;
	
	FILE *pFile = NULL;

	pFile = fopen("test.csv", "r" );
	if( pFile != NULL )
	{	
		while( !feof( pFile ) ){
			fgets( str_tmp, 1024, pFile );			
			//printf( "%s", str_tmp );
			
			cnt=0;
			sum=0;
			p = strtok(str_tmp, ",");
			while(p != NULL){
    			b[cnt]=atoi(p);
                cnt++;
                p=strtok(NULL, ",");
           }
		   for(i=0;i<cnt;i++){
              sum+=b[i];
              printf("%d ",b[i]);
           }    
           printf("토큰수 : %d , 합 : %d\n", cnt, sum);		 			
	  }		
	}
	fclose( pFile );
	
	return 0;
}
```
**[결과]**
![a3.jpg](https://cdn.steemitimages.com/DQmXyyCx8tUyssKvvZiXyEctNy2YpUUR9TtB53LUcEgoB9A/a3.jpg)

정상적으로 CSV 파일을 읽어와서 각 데이터를 쪼개고 그 데이터를 원하는 계산을 수행 해 보았습니다.


## 마무리
-----
strtok()함수의 원리를 생각하니 파일을 읽고 읽은 정보를 쪼개서 원하는 형태로 변환 시켜보고 싶은 생각이 문득 들어서 이렇게 실험을 해보았네요. 어떤 하나를 배우게 되면 그 원리를 잘 생각해보고 그 원리를 어디에 적용해 볼지 상상의 나래를 펼치면 이렇게 재밌는 실험을 할 수 있습니다.

---

#####  <sub> **Sponsored ( Powered by [dclick](https://www.dclick.io) )** </sub>
[![dclick-imagead](https://s3.ap-northeast-2.amazonaws.com/dclick/image/eversloth/1553073630328.jpg)](https://api.dclick.io/v1/c?x=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjIjoiY29kaW5nbWFuIiwicyI6ImMtY3N2LXN0cnRvay0tMTU1MzEyNjU4MzU4MyIsImEiOlsiaS0zMDAiXSwidXJsIjoiaHR0cHM6Ly9tb29ucmltLmlvL2tvIiwiaWF0IjoxNTUzMTI2NzQ4LCJleHAiOjE4Njg0ODY3NDh9.I-lDu62hJAnPFsYWyUl7BmNoGYB7ACiLKnfOHkLpPh0)
👍  , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorcodingman
permlinkc-csv-strtok--1553126583583
categorykr-dev
json_metadata{"tags":["kr-dev","jjangjjangman","busy","kr","kr-join"],"app":"dclick.app","format":"markdown","community":"busy","users":["codingman"],"links":["https://steemit.com/kr-dev/@codingman/c-strtok-1552953745917","https://www.dclick.io","https://api.dclick.io/v1/c?x=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjIjoiY29kaW5nbWFuIiwicyI6ImMtY3N2LXN0cnRvay0tMTU1MzEyNjU4MzU4MyIsImEiOlsiaS0xOTUiXSwidXJsIjoiaHR0cHM6Ly93d3cuZGNsaWNrLmlvL21vbmV0aXplIiwiaWF0IjoxNTUzMTI2NTgzLCJleHAiOjE4Njg0ODY1ODN9.UzB3cLYpnbH-aSGs0I5Cnke0lijiH45ZCntdk4ywXaA"],"image":["https://cdn.steemitimages.com/DQmSXSa4gmoDetq5dn7LL9eFY27ZJhcCGkFnGHUhA6Kfen2/a1.jpg","https://cdn.steemitimages.com/DQmXyyCx8tUyssKvvZiXyEctNy2YpUUR9TtB53LUcEgoB9A/a3.jpg","https://s3.ap-northeast-2.amazonaws.com/dclick/image/dclick/1552477485946.png"]}
created2019-03-21 00:03:03
last_update2019-03-21 00:05:54
depth0
children3
last_payout2019-03-28 00:03:03
cashout_time1969-12-31 23:59:59
total_payout_value1.501 HBD
curator_payout_value0.480 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length2,991
author_reputation23,188,231,710,844
root_title"[C언어] CSV 데이터 파일을 strtok()함수로 처리"
beneficiaries
0.
accountdclick
weight1,000
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id81,646,242
net_rshares3,384,725,480,443
author_curate_reward""
vote details (23)
@bukio ·
짱짱맨 호출에 응답하였습니다.
properties (22)
authorbukio
permlinkre-bukio-jjangjjangman-1553127531126
categorykr-dev
json_metadata"{"tags":["bukio", "jjangjjangman"],"app":"steemer/1.0"}"
created2019-03-21 00:18:51
last_update2019-03-21 00:18:51
depth1
children1
last_payout2019-03-28 00:18:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length16
author_reputation11,545,563,591,097
root_title"[C언어] CSV 데이터 파일을 strtok()함수로 처리"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id81,646,744
net_rshares0
@codingman ·
짱짱맨 방문 감사해요.
properties (22)
authorcodingman
permlinkre-bukio-re-bukio-jjangjjangman-1553127531126-20190321t031211125z
categorykr-dev
json_metadata{"tags":["kr-dev"],"app":"steemit/0.1"}
created2019-03-21 03:12:15
last_update2019-03-21 03:12:15
depth2
children0
last_payout2019-03-28 03:12:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length12
author_reputation23,188,231,710,844
root_title"[C언어] CSV 데이터 파일을 strtok()함수로 처리"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id81,652,567
net_rshares0
@steemitboard ·
Congratulations @codingman! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

<table><tr><td>https://steemitimages.com/60x70/http://steemitboard.com/@codingman/posts.png?201903210217</td><td>You published more than 400 posts. Your next target is to reach 450 posts.</td></tr>
</table>

<sub>_You can view [your badges on your Steem Board](https://steemitboard.com/@codingman) and compare to others on the [Steem Ranking](http://steemitboard.com/ranking/index.php?name=codingman)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>


To support your work, I also upvoted your post!


**Do not miss the last post from @steemitboard:**
<table><tr><td><a href="https://steemit.com/carnival/@steemitboard/carnival-challenge-here-are-the-winners"><img src="https://steemitimages.com/64x128/http://i.cubeupload.com/rltzHT.png"></a></td><td><a href="https://steemit.com/carnival/@steemitboard/carnival-challenge-here-are-the-winners">Carnival Challenge - Here are the winners</a></td></tr></table>

###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-codingman-20190321t025334000z
categorykr-dev
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2019-03-21 02:53:33
last_update2019-03-21 02:53:33
depth1
children0
last_payout2019-03-28 02:53:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,288
author_reputation38,975,615,169,260
root_title"[C언어] CSV 데이터 파일을 strtok()함수로 처리"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id81,651,770
net_rshares0