1

I have the following code below:

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

int main(void)
{
    int lendata;
    printf("Content-type:text/html\n\n");
    printf("<html><body>");
    lendata = atoi(getenv("CONTENT_LENGTH"));
    char *buf = malloc(lendata+1);
    int i=0;
    char *data;
    while((data=fgets(buf,lendata+1,stdin)) != NULL){
        char *lines[i];     
        lines[i] = strdup(data);
        printf("%s<br>",lines[i]);      
        i++;

}
    printf("%d, %d",lendata,i); 
    free(buf);
    printf("</body></html>");
    return 0;

}

I am trying to parse a *.csv file with different data types inside (i.e. character strings, intger ). How can I process each line in the file? Thanks!

3
  • correct the #include#include#include line! Commented Aug 16, 2013 at 2:58
  • How would I then go about it? Commented Aug 16, 2013 at 3:09
  • strdup() allocates a new string each time. You'd have to free those eventually. Commented Aug 16, 2013 at 3:15

1 Answer 1

1

Maybe this will be better....

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

int main(void)
{
    int lendata;
    printf("Content-type:text/html\n\n");
    printf("<html><body>");
    lendata = atoi(getenv("CONTENT_LENGTH"));
    char *buf = malloc(lendata+1);
    int i=0;
    char *data;
    while((data=fgets(buf,lendata+1,stdin)) != NULL){
          /*char *lines[i]; */       
          /* lines[i] = strdup(data); */  
          printf("%s<br>",data);        
          i++;  
    }
    printf("%d, %d",lendata,i); 
    free(buf);
    printf("</body></html>");
    return 0;

}

sscanf call returns number of entries that were matched.

numentries = sscanf(line,"%s,%s,%s,%s,%s",ent1,ent2,ent3,ent4,ent5);
Sign up to request clarification or add additional context in comments.

6 Comments

How can I then parse the content of the file?
Can I use sscanf to since the data inside the file are not numbers or integers?
Yes. Just be careful of spaces, if there are any. You might have to account fro them in the sscanf format.
@JKTA Everything you need to know about sscanf() for this (and frankly the rest of the C standard library) can be found at this link.
@JKTA sscanf(line,"%s, %s,%s"); /* space after first comma, no space after second */
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.