반응형

CSV 파일을 줄단위로 읽어서 공백을 제거한 후, 컬럼 별로 나누어서 출력하는 예제입니다.


다음 3곳의 코드 참고하여 작성했습니다.
https://stackoverflow.com/questions/12911299/read-csv-file-in-c
https://stackoverflow.com/questions/1726302/removing-spaces-from-a-string-in-c
https://www.ibm.com/docs/ko/i/7.3?topic=functions-strtok-tokenize-string

 


2021. 7. 3   최초작성

2021. 7. 4   컬럼 2개까지만 되는 버그 수정, 구조체로 결과 받아오도록 수정

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_DATA 3

struct data{
    char s[MAX_DATA][1024];
};

void remove_spaces(char* s) {
    const char* d = s;
    do {
        while (*d == ' ') {
            ++d;
        }
    } while (*s++ = *d++);
}

void getfield(char* line, struct data *d, int end_idx)
{
    int idx = 0;

    char *token = strtok(line, ",");

   do
   {
      //printf("token: %s\n", token);
      strcpy(d->s[idx++], token);
   }
   while ( idx != end_idx && (token = strtok(NULL, ",")));
   
}

int main()
{
    FILE* stream = fopen("location.csv", "r");

    char line[1024];
    while (fgets(line, 1024, stream))
    {
        remove_spaces(line);
        
        struct data d;

        char *tmp = strdup(line);
        getfield(tmp, &d, MAX_DATA);
        
        printf("[%s] [%s] [%s]\n", d.s[0], d.s[1], d.s[2]);
        
        free(tmp);
    }
}


실행 결과

[1] [37.40281] [126.97267]
[2] [37.40276] [126.97257]
[3] [37.40271] [126.97247]
[4] [37.40267] [126.97237]
[5] [37.40262] [126.97228]
[6] [37.40262] [126.97214]

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts