Search code examples
cfunctionwhile-loopnewlinefgets

I can't find a mistake in the function


I am writing analog linux comand cat by C but I can't find a mistake inside function, which must numerate non-empty strings. I get: segmentation fault, when I used this function (the code below):

void output_opt1_file(char *name_file) // функция открывает файл и нумерует только не пустые строки
{
    FILE *f = fopen(name_file, "rt");

    if (f != NULL) {
        char *string;
        fgets(string, 100, f);
        int i = 1;
        while (fgets(string, 100, f) != NULL) {
            if (strlen(string) == 0) //if (string[0] == '\n')
            {
                printf("%s", string);//puts(string);
            }
            else
            {
                printf("%d%c", i, ' ');
                ++i;
                printf("%s", string);//puts(string);                    
            }
        }
        fclose(f);
    }
}

I need help for seeking my mistake.


Solution

  • Your code is wrong at least by two reasons.

    The first one is that the pointer string is uninitialized.

    char *string;
    

    You need to declare a character array instead of the pointer like for example

    char string[100];
    

    The second problem is that this if statement

     if (strlen(string) == 0) 
    

    will never evaluate to logical true because the function fgets at least can read a new line character '\n' for an empty string from a text file.

    Instead you could write

     if ( string[0] == '\n') 
    

    And this call before the while loop

        fgets(string, 100, f);
        int i = 1;
        while (fgets(string, 100, f) != NULL) {
    

    skips the first record.

    Pay attention to that in general a record in a file can be larger than or equal to 100 characters. For example if a record in a file contains exactly 99 characters plus the new line character '\n' then your function will consider this record as two records: the new line character of the record will be considered as a separated second empty record.