0

I want to split value in .csv

"word1","word2","word3","a,b,c,d,e"

"ab,bc","word2","word3","a,b,c,d,e"

to

word1

word2

word3

a,b,c,d,e

ab,bc

word2

word3

a,b,c,d,e

int main(void)
{
char line_buf[_POSIX2_LINE_MAX];
        char *p, *np;
        FILE *fp;
        fp = fopen("a.csv", "r");
        if (fp == NULL)
        {
            printf("\n Failed to open file!");
        }
        else
        {
            while ((fgets(line_buf, _POSIX2_LINE_MAX, fp)) != NULL)
            {
                p = line_buf;
                while ((np = index(p, ',')) != NULL)
                {
                    *np = '\n';
                }
                printf("%s", p);
            }
            fclose(fp);
            return 0;
        }
    }
  • If using `strtok()` pass delimiter `"\","` for every field except the final one, which should not have comma but newline so `"\"\n"`. Your post is unclear though, whether the input CSV file contains the `"` symbols. – Weather Vane Dec 23 '20 at 17:41
  • Why are you using the value `MAXPATHLEN` for the size of the line buffer. This does vary between machines/OSs – Ed Heal Dec 23 '20 at 17:50
  • 1
    `Failed to open file!` is the canonical example of a useless error message. `if( (fp = fopen(path, mode)) == NULL ){ perror(path); ...` Write the error message to stderr and make it informative. Use `perror` – William Pursell Dec 23 '20 at 17:56
  • 1
    Why read lines if you are only inspecting one character at a time? – wildplasser Dec 23 '20 at 18:35

0 Answers0