Question

For the C project coming up, the goal is to read in a CSV file with the first two lines listing the row and column lengths like

attributes: 23
lines: 1000
e,x,y,n,t,l,f,c,b,p,e,r,s,y,w,w,p,w,o,p,n,y,p
e,b,y,y,t,l,f,c,b,n,e,c,s,s,w,w,p,w,o,p,n,s,m
e,x,f,y,t,l,f,w,n,w,t,b,s,s,w,w,p,w,o,p,n,v,d
e,s,f,g,f,n,f,c,n,k,e,e,s,s,w,w,p,w,o,p,k,v,u

The thing is, I don't know if future file inputs will be of the same row/column lengths, so I'm implementing a determineFormat function to read those first two lines, which will be used for building the data structures.

In order to do this, I need to match a substring to the current line. If it matches, then fscanf is used to read in the line and extract the length integers. However, this code isn't working, as the entire strstr function is getting skipped over in ddd.

int lineCount, attrCount; //global variables

void determineFormats(FILE *incoming){

    char *curLine= emalloc(CLINPUT);
    int i;
    char *ptr=NULL;

    for (i=0; i<2; i++){
        if (fgets(curLine, CLINPUT, incoming) != NULL){
            ptr= strstr(curLine, "attrib");  //this line is skipped over

            if (ptr!= NULL)
                fscanf(incoming, "attributes: %d", &attrCount);

            else 
                fscanf(incoming, "lines: %d", &lineCount);  

        }
    }

    printf("Attribute Count for the input file is: %d\n", attrCount);
    printf("Line count is: %d\n", lineCount);

}

My thinking for the if/else block is since there are only two lines of interest to this function, and they're both at the head of the file, just scan each line and test if the string matches. If it does, then the non-null conditional is run, otherwise the other conditional is executed. However, in this case, the strstr function is getting skipped.

Extra Info

Some of the comments made me go back and double check.

CLINPUT is defined to be 100, or roughly 40% again the number of characters to read from each line.

This is the output from ddd when ptr= strstr(curLine, "attrib"); is called:

0xb7eeaff0 in strstr () from /lib/libc.so.6
Single stepping until exit from function strstr,
which has no line number information.

Once this happens, the line indicator disappears, and single stepping (F5) from that point returns to the calling function.

Was it helpful?

Solution

strstr is working good. Problem is that fscanf will read next line since current already read.

Here's more correct way

for (i=0; i<2; i++){
    if (fgets(curLine, CLINPUT, incoming) != NULL){
        if (strstr(curLine, "attributes:")) {
            sscanf(curLine, "attributes: %d", &attrCount);
        } else if (strstr(curLine, "lines:")) {
            sscanf(curLine, "lines: %d", &lineCount);  
        }

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top