Question

Hi all I'm trying to write a function that returns the line of data and returns it in a String. Below is my code and I'm not sure why it's not working. I've added in a printf function and when I call the function nothing prints out.?

EDIT (cause i can't answer yet) - Thanks for your replies. When I change char c to char *c it still doesn't work. I just need to read the line into a string and return it.

char* getLine(FILE *file, int lineNum){

    char c;
    int lineCount=0, size = 1;
    char *line = NULL;
    line = malloc(sizeof(char)*size);
    while ((c=getc(file)) != EOF){

        if (c=='\n'){
            ++lineCount;
            continue;
        }
        if (lineCount==lineNum){
            size += 1;
            line = realloc(line, size*sizeof(char));
            strcat(line, c);
            printf("Line: %s\n", line);
        }
    }
    return line;
}
Was it helpful?

Solution 2

It's not very efficient, but it should do what you want:

Note that lineCount starts at 0. (The first line is line 0).

char* getLine(FILE *file, int lineNum){
    char c;
    int lineCount=0, size = 0; // start size at zero, not one
    char *line = NULL;

    while ((c=getc(file)) != EOF){
        if (lineCount==lineNum){
            size += 1;
            if(line == NULL) {
                line = calloc(sizeof(char), size); 
            } else {
                line = realloc(line, size*sizeof(char));
            }
            char ac[2] = { c, 0 }; // this line is new
            strcat(line, ac); // ac is new here
            printf("Line: %s\n", line);
            if(c == '\n') {
                return line;
            }
        }
        if (c=='\n'){
            ++lineCount;
        }
    }
    printf("Could not find line %d\n", lineNum);
    return NULL;
}

OTHER TIPS

Variable c is not of type const char * See strcat documentation

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