Read a file line by line and scan each character seperated by comma into seperate variables in C





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















Have to read file.txt with format as mentioned below:
12AA,abc12 n
4CCC,cde15 n



I want to read the file line by line and store comma separated values in separate variables.



fp = fopen("file.txt", "r");

while(fgets(buffer, 255, (FILE*) fp))
{
fscanf(fp, "%s %s", acc_no, package);
printf("%sn", acc_no);
printf("%sn", package);
}

fclose(fp);


I would like not only just read and print the variable but, also, to store them in separate variables. Suggestion on how to do that?










share|improve this question

























  • strtok may help.

    – Biswapriyo
    Nov 17 '18 at 7:12











  • so, if every line is a variable, you can read before the whole file and, after, you can use malloc to allocate all the variable in the heap. Bring the pointer back to the beginning of the file and perform the operation of storing the string in the variable you have allocated. That's all, nothing more! (Be careful: if you need a value and not a string, you need to convert them using the function of the C library: strod(...) is one of them - stackoverflow.com/questions/7951019/…)

    – Leos313
    Nov 17 '18 at 7:40













  • This code smells: while(fgets(buffer, 255, (FILE*) fp)) Why are you casting something that should already be a FILE * to a FILE *?

    – Andrew Henle
    Nov 17 '18 at 13:47


















1















Have to read file.txt with format as mentioned below:
12AA,abc12 n
4CCC,cde15 n



I want to read the file line by line and store comma separated values in separate variables.



fp = fopen("file.txt", "r");

while(fgets(buffer, 255, (FILE*) fp))
{
fscanf(fp, "%s %s", acc_no, package);
printf("%sn", acc_no);
printf("%sn", package);
}

fclose(fp);


I would like not only just read and print the variable but, also, to store them in separate variables. Suggestion on how to do that?










share|improve this question

























  • strtok may help.

    – Biswapriyo
    Nov 17 '18 at 7:12











  • so, if every line is a variable, you can read before the whole file and, after, you can use malloc to allocate all the variable in the heap. Bring the pointer back to the beginning of the file and perform the operation of storing the string in the variable you have allocated. That's all, nothing more! (Be careful: if you need a value and not a string, you need to convert them using the function of the C library: strod(...) is one of them - stackoverflow.com/questions/7951019/…)

    – Leos313
    Nov 17 '18 at 7:40













  • This code smells: while(fgets(buffer, 255, (FILE*) fp)) Why are you casting something that should already be a FILE * to a FILE *?

    – Andrew Henle
    Nov 17 '18 at 13:47














1












1








1








Have to read file.txt with format as mentioned below:
12AA,abc12 n
4CCC,cde15 n



I want to read the file line by line and store comma separated values in separate variables.



fp = fopen("file.txt", "r");

while(fgets(buffer, 255, (FILE*) fp))
{
fscanf(fp, "%s %s", acc_no, package);
printf("%sn", acc_no);
printf("%sn", package);
}

fclose(fp);


I would like not only just read and print the variable but, also, to store them in separate variables. Suggestion on how to do that?










share|improve this question
















Have to read file.txt with format as mentioned below:
12AA,abc12 n
4CCC,cde15 n



I want to read the file line by line and store comma separated values in separate variables.



fp = fopen("file.txt", "r");

while(fgets(buffer, 255, (FILE*) fp))
{
fscanf(fp, "%s %s", acc_no, package);
printf("%sn", acc_no);
printf("%sn", package);
}

fclose(fp);


I would like not only just read and print the variable but, also, to store them in separate variables. Suggestion on how to do that?







c file-io






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 17 '18 at 13:45









Leos313

1,67311536




1,67311536










asked Nov 17 '18 at 6:57









Mufaria RazakMufaria Razak

155




155













  • strtok may help.

    – Biswapriyo
    Nov 17 '18 at 7:12











  • so, if every line is a variable, you can read before the whole file and, after, you can use malloc to allocate all the variable in the heap. Bring the pointer back to the beginning of the file and perform the operation of storing the string in the variable you have allocated. That's all, nothing more! (Be careful: if you need a value and not a string, you need to convert them using the function of the C library: strod(...) is one of them - stackoverflow.com/questions/7951019/…)

    – Leos313
    Nov 17 '18 at 7:40













  • This code smells: while(fgets(buffer, 255, (FILE*) fp)) Why are you casting something that should already be a FILE * to a FILE *?

    – Andrew Henle
    Nov 17 '18 at 13:47



















  • strtok may help.

    – Biswapriyo
    Nov 17 '18 at 7:12











  • so, if every line is a variable, you can read before the whole file and, after, you can use malloc to allocate all the variable in the heap. Bring the pointer back to the beginning of the file and perform the operation of storing the string in the variable you have allocated. That's all, nothing more! (Be careful: if you need a value and not a string, you need to convert them using the function of the C library: strod(...) is one of them - stackoverflow.com/questions/7951019/…)

    – Leos313
    Nov 17 '18 at 7:40













  • This code smells: while(fgets(buffer, 255, (FILE*) fp)) Why are you casting something that should already be a FILE * to a FILE *?

    – Andrew Henle
    Nov 17 '18 at 13:47

















strtok may help.

– Biswapriyo
Nov 17 '18 at 7:12





strtok may help.

– Biswapriyo
Nov 17 '18 at 7:12













so, if every line is a variable, you can read before the whole file and, after, you can use malloc to allocate all the variable in the heap. Bring the pointer back to the beginning of the file and perform the operation of storing the string in the variable you have allocated. That's all, nothing more! (Be careful: if you need a value and not a string, you need to convert them using the function of the C library: strod(...) is one of them - stackoverflow.com/questions/7951019/…)

– Leos313
Nov 17 '18 at 7:40







so, if every line is a variable, you can read before the whole file and, after, you can use malloc to allocate all the variable in the heap. Bring the pointer back to the beginning of the file and perform the operation of storing the string in the variable you have allocated. That's all, nothing more! (Be careful: if you need a value and not a string, you need to convert them using the function of the C library: strod(...) is one of them - stackoverflow.com/questions/7951019/…)

– Leos313
Nov 17 '18 at 7:40















This code smells: while(fgets(buffer, 255, (FILE*) fp)) Why are you casting something that should already be a FILE * to a FILE *?

– Andrew Henle
Nov 17 '18 at 13:47





This code smells: while(fgets(buffer, 255, (FILE*) fp)) Why are you casting something that should already be a FILE * to a FILE *?

– Andrew Henle
Nov 17 '18 at 13:47












2 Answers
2






active

oldest

votes


















3














strchr() can help:



while (fgets(str, sizeof str, fp)) {
char *arr[2], *ptr;

arr[0] = str;
if ((ptr = strchr(str, ','))) {
arr[1] = ptr + 1;
*ptr = '';
} else {
exit(EXIT_FAILURE);
}
printf("<%s> <%s>n", arr[0], arr[1]);
}


Notice that you may need to strip the trailing newline lefted by fgets() or ommit the n in printf



If you need to store those strings in fresh memory, then there is a bit more of work, you can realloc() or use a linked list (always prefer linked lists when you don't know the number of lines before-hand):



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

struct node {
void *data;
struct node *next;
};

/* Returns a pointer to an allocated string */
extern char *strdup(const char *);

/* Insert a node and returns a pointer to the data */
static void *enqueue(struct node **root, void *data)
{
struct node *node;

if (root == NULL) {
return NULL;
}
node = malloc(sizeof *node);
if (node == NULL) {
return NULL;
}
if (*root == NULL) {
node->next = node;
} else {
node->next = (*root)->next;
(*root)->next = node;
}
node->data = data;
*root = node;
return data;
}

/* Delete a node and returns a pointer to the data */
static void *dequeue(struct node **root)
{
struct node *node;
void *data = NULL;

if (root == NULL) {
return NULL;
}
node = *root;
if (node != NULL) {
node = node->next;
data = node->data;
if (*root == node) {
*root = NULL;
} else {
(*root)->next = node->next;
}
free(node);
}
return data;
}

int main(void)
{
struct node *head = NULL;
char str[256];
char **arr;
char *ptr;

/* While we don't hit EOF */
while (fgets(str, sizeof str, stdin)) {
/* Reserve space for 2 pointers */
arr = malloc(sizeof(*arr) * 2);
if (arr == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
/* If we find a comma */
if ((ptr = strchr(str, ','))) {
/* Store the second string */
arr[1] = strdup(ptr + 1);
if (arr[1] == NULL) {
perror("strdup");
exit(EXIT_FAILURE);
}
/* Strip the string */
*ptr = '';
/* If we don't find a comma */
} else {
exit(EXIT_FAILURE);
}
/* Store the first string */
arr[0] = strdup(str);
if (arr[0] == NULL) {
perror("strdup");
exit(EXIT_FAILURE);
}
/* Add a node to the queue*/
if (enqueue(&head, arr) == NULL) {
perror("enqueue");
exit(EXIT_FAILURE);
}
}
/* While nodes in queue show the data and free */
while ((arr = dequeue(&head))) {
printf("%s %s", arr[0], arr[1]);
free(arr[0]);
free(arr[1]);
free(arr);
}
return 0;
}





share|improve this answer





















  • 2





    +1, it is a complete answer. To add some comment in the code to explain what you do (for newbies) may be an added value

    – Leos313
    Nov 17 '18 at 9:07






  • 2





    @Leos313, yes, added some comments (even if the function names are pretty descriptive :P)

    – Keine Lust
    Nov 17 '18 at 9:20



















0














You can use fscanf format strings instead.



fscanf(fp, " %[^,n], %[^n]", values[i][0], values[i][1]);


Like so



#include <stdio.h>

int main() {
FILE* fp = fopen("file.txt", "r");

char values[1000][2][100];

int i = 0;
while(!feof(fp)) {
fscanf(fp, " %[^,n], %[^n]", values[i][0], values[i][1]);
printf("%s %sn", values[i][0], values[i][1]);
}

}


The fscanf format string:





  • <space> = skip leading whitespaces (like a newline from the line before)


  • %[^,n] = read a string until, but not including, "," or "n"


  • , = expect a comma and discard it


  • %[^n] = read a string until, but not including, "n"


values is a 2D array of strings, with 1000 rows and 2 columns. Each element is a string of maximum length of 100 chars.



Also, if you use %m[^,n] instead, fscanf will allocate the memory for the string read.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53348989%2fread-a-file-line-by-line-and-scan-each-character-seperated-by-comma-into-seperat%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    strchr() can help:



    while (fgets(str, sizeof str, fp)) {
    char *arr[2], *ptr;

    arr[0] = str;
    if ((ptr = strchr(str, ','))) {
    arr[1] = ptr + 1;
    *ptr = '';
    } else {
    exit(EXIT_FAILURE);
    }
    printf("<%s> <%s>n", arr[0], arr[1]);
    }


    Notice that you may need to strip the trailing newline lefted by fgets() or ommit the n in printf



    If you need to store those strings in fresh memory, then there is a bit more of work, you can realloc() or use a linked list (always prefer linked lists when you don't know the number of lines before-hand):



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

    struct node {
    void *data;
    struct node *next;
    };

    /* Returns a pointer to an allocated string */
    extern char *strdup(const char *);

    /* Insert a node and returns a pointer to the data */
    static void *enqueue(struct node **root, void *data)
    {
    struct node *node;

    if (root == NULL) {
    return NULL;
    }
    node = malloc(sizeof *node);
    if (node == NULL) {
    return NULL;
    }
    if (*root == NULL) {
    node->next = node;
    } else {
    node->next = (*root)->next;
    (*root)->next = node;
    }
    node->data = data;
    *root = node;
    return data;
    }

    /* Delete a node and returns a pointer to the data */
    static void *dequeue(struct node **root)
    {
    struct node *node;
    void *data = NULL;

    if (root == NULL) {
    return NULL;
    }
    node = *root;
    if (node != NULL) {
    node = node->next;
    data = node->data;
    if (*root == node) {
    *root = NULL;
    } else {
    (*root)->next = node->next;
    }
    free(node);
    }
    return data;
    }

    int main(void)
    {
    struct node *head = NULL;
    char str[256];
    char **arr;
    char *ptr;

    /* While we don't hit EOF */
    while (fgets(str, sizeof str, stdin)) {
    /* Reserve space for 2 pointers */
    arr = malloc(sizeof(*arr) * 2);
    if (arr == NULL) {
    perror("malloc");
    exit(EXIT_FAILURE);
    }
    /* If we find a comma */
    if ((ptr = strchr(str, ','))) {
    /* Store the second string */
    arr[1] = strdup(ptr + 1);
    if (arr[1] == NULL) {
    perror("strdup");
    exit(EXIT_FAILURE);
    }
    /* Strip the string */
    *ptr = '';
    /* If we don't find a comma */
    } else {
    exit(EXIT_FAILURE);
    }
    /* Store the first string */
    arr[0] = strdup(str);
    if (arr[0] == NULL) {
    perror("strdup");
    exit(EXIT_FAILURE);
    }
    /* Add a node to the queue*/
    if (enqueue(&head, arr) == NULL) {
    perror("enqueue");
    exit(EXIT_FAILURE);
    }
    }
    /* While nodes in queue show the data and free */
    while ((arr = dequeue(&head))) {
    printf("%s %s", arr[0], arr[1]);
    free(arr[0]);
    free(arr[1]);
    free(arr);
    }
    return 0;
    }





    share|improve this answer





















    • 2





      +1, it is a complete answer. To add some comment in the code to explain what you do (for newbies) may be an added value

      – Leos313
      Nov 17 '18 at 9:07






    • 2





      @Leos313, yes, added some comments (even if the function names are pretty descriptive :P)

      – Keine Lust
      Nov 17 '18 at 9:20
















    3














    strchr() can help:



    while (fgets(str, sizeof str, fp)) {
    char *arr[2], *ptr;

    arr[0] = str;
    if ((ptr = strchr(str, ','))) {
    arr[1] = ptr + 1;
    *ptr = '';
    } else {
    exit(EXIT_FAILURE);
    }
    printf("<%s> <%s>n", arr[0], arr[1]);
    }


    Notice that you may need to strip the trailing newline lefted by fgets() or ommit the n in printf



    If you need to store those strings in fresh memory, then there is a bit more of work, you can realloc() or use a linked list (always prefer linked lists when you don't know the number of lines before-hand):



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

    struct node {
    void *data;
    struct node *next;
    };

    /* Returns a pointer to an allocated string */
    extern char *strdup(const char *);

    /* Insert a node and returns a pointer to the data */
    static void *enqueue(struct node **root, void *data)
    {
    struct node *node;

    if (root == NULL) {
    return NULL;
    }
    node = malloc(sizeof *node);
    if (node == NULL) {
    return NULL;
    }
    if (*root == NULL) {
    node->next = node;
    } else {
    node->next = (*root)->next;
    (*root)->next = node;
    }
    node->data = data;
    *root = node;
    return data;
    }

    /* Delete a node and returns a pointer to the data */
    static void *dequeue(struct node **root)
    {
    struct node *node;
    void *data = NULL;

    if (root == NULL) {
    return NULL;
    }
    node = *root;
    if (node != NULL) {
    node = node->next;
    data = node->data;
    if (*root == node) {
    *root = NULL;
    } else {
    (*root)->next = node->next;
    }
    free(node);
    }
    return data;
    }

    int main(void)
    {
    struct node *head = NULL;
    char str[256];
    char **arr;
    char *ptr;

    /* While we don't hit EOF */
    while (fgets(str, sizeof str, stdin)) {
    /* Reserve space for 2 pointers */
    arr = malloc(sizeof(*arr) * 2);
    if (arr == NULL) {
    perror("malloc");
    exit(EXIT_FAILURE);
    }
    /* If we find a comma */
    if ((ptr = strchr(str, ','))) {
    /* Store the second string */
    arr[1] = strdup(ptr + 1);
    if (arr[1] == NULL) {
    perror("strdup");
    exit(EXIT_FAILURE);
    }
    /* Strip the string */
    *ptr = '';
    /* If we don't find a comma */
    } else {
    exit(EXIT_FAILURE);
    }
    /* Store the first string */
    arr[0] = strdup(str);
    if (arr[0] == NULL) {
    perror("strdup");
    exit(EXIT_FAILURE);
    }
    /* Add a node to the queue*/
    if (enqueue(&head, arr) == NULL) {
    perror("enqueue");
    exit(EXIT_FAILURE);
    }
    }
    /* While nodes in queue show the data and free */
    while ((arr = dequeue(&head))) {
    printf("%s %s", arr[0], arr[1]);
    free(arr[0]);
    free(arr[1]);
    free(arr);
    }
    return 0;
    }





    share|improve this answer





















    • 2





      +1, it is a complete answer. To add some comment in the code to explain what you do (for newbies) may be an added value

      – Leos313
      Nov 17 '18 at 9:07






    • 2





      @Leos313, yes, added some comments (even if the function names are pretty descriptive :P)

      – Keine Lust
      Nov 17 '18 at 9:20














    3












    3








    3







    strchr() can help:



    while (fgets(str, sizeof str, fp)) {
    char *arr[2], *ptr;

    arr[0] = str;
    if ((ptr = strchr(str, ','))) {
    arr[1] = ptr + 1;
    *ptr = '';
    } else {
    exit(EXIT_FAILURE);
    }
    printf("<%s> <%s>n", arr[0], arr[1]);
    }


    Notice that you may need to strip the trailing newline lefted by fgets() or ommit the n in printf



    If you need to store those strings in fresh memory, then there is a bit more of work, you can realloc() or use a linked list (always prefer linked lists when you don't know the number of lines before-hand):



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

    struct node {
    void *data;
    struct node *next;
    };

    /* Returns a pointer to an allocated string */
    extern char *strdup(const char *);

    /* Insert a node and returns a pointer to the data */
    static void *enqueue(struct node **root, void *data)
    {
    struct node *node;

    if (root == NULL) {
    return NULL;
    }
    node = malloc(sizeof *node);
    if (node == NULL) {
    return NULL;
    }
    if (*root == NULL) {
    node->next = node;
    } else {
    node->next = (*root)->next;
    (*root)->next = node;
    }
    node->data = data;
    *root = node;
    return data;
    }

    /* Delete a node and returns a pointer to the data */
    static void *dequeue(struct node **root)
    {
    struct node *node;
    void *data = NULL;

    if (root == NULL) {
    return NULL;
    }
    node = *root;
    if (node != NULL) {
    node = node->next;
    data = node->data;
    if (*root == node) {
    *root = NULL;
    } else {
    (*root)->next = node->next;
    }
    free(node);
    }
    return data;
    }

    int main(void)
    {
    struct node *head = NULL;
    char str[256];
    char **arr;
    char *ptr;

    /* While we don't hit EOF */
    while (fgets(str, sizeof str, stdin)) {
    /* Reserve space for 2 pointers */
    arr = malloc(sizeof(*arr) * 2);
    if (arr == NULL) {
    perror("malloc");
    exit(EXIT_FAILURE);
    }
    /* If we find a comma */
    if ((ptr = strchr(str, ','))) {
    /* Store the second string */
    arr[1] = strdup(ptr + 1);
    if (arr[1] == NULL) {
    perror("strdup");
    exit(EXIT_FAILURE);
    }
    /* Strip the string */
    *ptr = '';
    /* If we don't find a comma */
    } else {
    exit(EXIT_FAILURE);
    }
    /* Store the first string */
    arr[0] = strdup(str);
    if (arr[0] == NULL) {
    perror("strdup");
    exit(EXIT_FAILURE);
    }
    /* Add a node to the queue*/
    if (enqueue(&head, arr) == NULL) {
    perror("enqueue");
    exit(EXIT_FAILURE);
    }
    }
    /* While nodes in queue show the data and free */
    while ((arr = dequeue(&head))) {
    printf("%s %s", arr[0], arr[1]);
    free(arr[0]);
    free(arr[1]);
    free(arr);
    }
    return 0;
    }





    share|improve this answer















    strchr() can help:



    while (fgets(str, sizeof str, fp)) {
    char *arr[2], *ptr;

    arr[0] = str;
    if ((ptr = strchr(str, ','))) {
    arr[1] = ptr + 1;
    *ptr = '';
    } else {
    exit(EXIT_FAILURE);
    }
    printf("<%s> <%s>n", arr[0], arr[1]);
    }


    Notice that you may need to strip the trailing newline lefted by fgets() or ommit the n in printf



    If you need to store those strings in fresh memory, then there is a bit more of work, you can realloc() or use a linked list (always prefer linked lists when you don't know the number of lines before-hand):



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

    struct node {
    void *data;
    struct node *next;
    };

    /* Returns a pointer to an allocated string */
    extern char *strdup(const char *);

    /* Insert a node and returns a pointer to the data */
    static void *enqueue(struct node **root, void *data)
    {
    struct node *node;

    if (root == NULL) {
    return NULL;
    }
    node = malloc(sizeof *node);
    if (node == NULL) {
    return NULL;
    }
    if (*root == NULL) {
    node->next = node;
    } else {
    node->next = (*root)->next;
    (*root)->next = node;
    }
    node->data = data;
    *root = node;
    return data;
    }

    /* Delete a node and returns a pointer to the data */
    static void *dequeue(struct node **root)
    {
    struct node *node;
    void *data = NULL;

    if (root == NULL) {
    return NULL;
    }
    node = *root;
    if (node != NULL) {
    node = node->next;
    data = node->data;
    if (*root == node) {
    *root = NULL;
    } else {
    (*root)->next = node->next;
    }
    free(node);
    }
    return data;
    }

    int main(void)
    {
    struct node *head = NULL;
    char str[256];
    char **arr;
    char *ptr;

    /* While we don't hit EOF */
    while (fgets(str, sizeof str, stdin)) {
    /* Reserve space for 2 pointers */
    arr = malloc(sizeof(*arr) * 2);
    if (arr == NULL) {
    perror("malloc");
    exit(EXIT_FAILURE);
    }
    /* If we find a comma */
    if ((ptr = strchr(str, ','))) {
    /* Store the second string */
    arr[1] = strdup(ptr + 1);
    if (arr[1] == NULL) {
    perror("strdup");
    exit(EXIT_FAILURE);
    }
    /* Strip the string */
    *ptr = '';
    /* If we don't find a comma */
    } else {
    exit(EXIT_FAILURE);
    }
    /* Store the first string */
    arr[0] = strdup(str);
    if (arr[0] == NULL) {
    perror("strdup");
    exit(EXIT_FAILURE);
    }
    /* Add a node to the queue*/
    if (enqueue(&head, arr) == NULL) {
    perror("enqueue");
    exit(EXIT_FAILURE);
    }
    }
    /* While nodes in queue show the data and free */
    while ((arr = dequeue(&head))) {
    printf("%s %s", arr[0], arr[1]);
    free(arr[0]);
    free(arr[1]);
    free(arr);
    }
    return 0;
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 17 '18 at 9:19

























    answered Nov 17 '18 at 7:42









    Keine LustKeine Lust

    27.2k43367




    27.2k43367








    • 2





      +1, it is a complete answer. To add some comment in the code to explain what you do (for newbies) may be an added value

      – Leos313
      Nov 17 '18 at 9:07






    • 2





      @Leos313, yes, added some comments (even if the function names are pretty descriptive :P)

      – Keine Lust
      Nov 17 '18 at 9:20














    • 2





      +1, it is a complete answer. To add some comment in the code to explain what you do (for newbies) may be an added value

      – Leos313
      Nov 17 '18 at 9:07






    • 2





      @Leos313, yes, added some comments (even if the function names are pretty descriptive :P)

      – Keine Lust
      Nov 17 '18 at 9:20








    2




    2





    +1, it is a complete answer. To add some comment in the code to explain what you do (for newbies) may be an added value

    – Leos313
    Nov 17 '18 at 9:07





    +1, it is a complete answer. To add some comment in the code to explain what you do (for newbies) may be an added value

    – Leos313
    Nov 17 '18 at 9:07




    2




    2





    @Leos313, yes, added some comments (even if the function names are pretty descriptive :P)

    – Keine Lust
    Nov 17 '18 at 9:20





    @Leos313, yes, added some comments (even if the function names are pretty descriptive :P)

    – Keine Lust
    Nov 17 '18 at 9:20













    0














    You can use fscanf format strings instead.



    fscanf(fp, " %[^,n], %[^n]", values[i][0], values[i][1]);


    Like so



    #include <stdio.h>

    int main() {
    FILE* fp = fopen("file.txt", "r");

    char values[1000][2][100];

    int i = 0;
    while(!feof(fp)) {
    fscanf(fp, " %[^,n], %[^n]", values[i][0], values[i][1]);
    printf("%s %sn", values[i][0], values[i][1]);
    }

    }


    The fscanf format string:





    • <space> = skip leading whitespaces (like a newline from the line before)


    • %[^,n] = read a string until, but not including, "," or "n"


    • , = expect a comma and discard it


    • %[^n] = read a string until, but not including, "n"


    values is a 2D array of strings, with 1000 rows and 2 columns. Each element is a string of maximum length of 100 chars.



    Also, if you use %m[^,n] instead, fscanf will allocate the memory for the string read.






    share|improve this answer




























      0














      You can use fscanf format strings instead.



      fscanf(fp, " %[^,n], %[^n]", values[i][0], values[i][1]);


      Like so



      #include <stdio.h>

      int main() {
      FILE* fp = fopen("file.txt", "r");

      char values[1000][2][100];

      int i = 0;
      while(!feof(fp)) {
      fscanf(fp, " %[^,n], %[^n]", values[i][0], values[i][1]);
      printf("%s %sn", values[i][0], values[i][1]);
      }

      }


      The fscanf format string:





      • <space> = skip leading whitespaces (like a newline from the line before)


      • %[^,n] = read a string until, but not including, "," or "n"


      • , = expect a comma and discard it


      • %[^n] = read a string until, but not including, "n"


      values is a 2D array of strings, with 1000 rows and 2 columns. Each element is a string of maximum length of 100 chars.



      Also, if you use %m[^,n] instead, fscanf will allocate the memory for the string read.






      share|improve this answer


























        0












        0








        0







        You can use fscanf format strings instead.



        fscanf(fp, " %[^,n], %[^n]", values[i][0], values[i][1]);


        Like so



        #include <stdio.h>

        int main() {
        FILE* fp = fopen("file.txt", "r");

        char values[1000][2][100];

        int i = 0;
        while(!feof(fp)) {
        fscanf(fp, " %[^,n], %[^n]", values[i][0], values[i][1]);
        printf("%s %sn", values[i][0], values[i][1]);
        }

        }


        The fscanf format string:





        • <space> = skip leading whitespaces (like a newline from the line before)


        • %[^,n] = read a string until, but not including, "," or "n"


        • , = expect a comma and discard it


        • %[^n] = read a string until, but not including, "n"


        values is a 2D array of strings, with 1000 rows and 2 columns. Each element is a string of maximum length of 100 chars.



        Also, if you use %m[^,n] instead, fscanf will allocate the memory for the string read.






        share|improve this answer













        You can use fscanf format strings instead.



        fscanf(fp, " %[^,n], %[^n]", values[i][0], values[i][1]);


        Like so



        #include <stdio.h>

        int main() {
        FILE* fp = fopen("file.txt", "r");

        char values[1000][2][100];

        int i = 0;
        while(!feof(fp)) {
        fscanf(fp, " %[^,n], %[^n]", values[i][0], values[i][1]);
        printf("%s %sn", values[i][0], values[i][1]);
        }

        }


        The fscanf format string:





        • <space> = skip leading whitespaces (like a newline from the line before)


        • %[^,n] = read a string until, but not including, "," or "n"


        • , = expect a comma and discard it


        • %[^n] = read a string until, but not including, "n"


        values is a 2D array of strings, with 1000 rows and 2 columns. Each element is a string of maximum length of 100 chars.



        Also, if you use %m[^,n] instead, fscanf will allocate the memory for the string read.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 17 '18 at 9:56









        Aravind VogguAravind Voggu

        898514




        898514






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53348989%2fread-a-file-line-by-line-and-scan-each-character-seperated-by-comma-into-seperat%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python