Search code examples
cioansi-c

How can I insert a char at the beginning of a line rather than at the end?


I am a beginner to C, and essentially, I am trying to read a file char by char, and echo the characters to the output, but also, at the start of every line, include the line number. I have managed to figure out how to count the lines, but when I attempt to insert the line number, I can't figure out how to get it to insert on the next line, rather than immediately upon encountering the newline.

Here is my code:

int main() {
    int c, nl;

    nl = 1; 
    FILE *file;
    file = fopen("testWords.in", "r");

    if (file) {
        printf("%d. ", nl);
        while((c = getc(file)) != EOF) {
            if (c == '\n') {
                ++nl;
                printf("%d", nl);
            }
            printf("%c", c);
        }
        fclose(file);
    }
}

And here is the output:

1. The Three Laws of Robotics:2
First: A robot may not injure a human being or, through inaction,3
   allow a human being to come to harm;4
Second: A robot must obey the orders given it by human beings5
   except where such orders would conflict with the First Law;6
Third: A robot must protect its own existence as long as7
such protection does not conflict with the First or Second Law;8
The Zeroth Law: A robot may not harm humanity, or, by inaction,9
    allow humanity to come to harm.10
    -- Isaac Asimov, I, Robot11


Solution

  • I believe you want to print the new line character, \n, before you print the line number. You can fix this simply by moving your print char line above the if statement.

    int main(void) {
        int c, nl;
    
        nl = 1; 
        FILE *file;
        file = fopen("testWords.in", "r");
    
        if (file) {
            printf("%d. ", nl);
            while((c = getc(file)) != EOF) {
                printf("%c", c);
                if (c == '\n') {
                    ++nl;
                    printf("%d", nl);
                }
            }
            fclose(file);
        }
    
        return 0;
    }
    

    Without changing what you have too much, you can prevent printing the extra line number by logging the previous char. Wait to print the line number until the last char was \n and you are on a new line. This way the EOF will trigger before an extraneous line number is printed.

    #include <stdio.h>
    
    int main(void) {
        int c, nl, p;
    
        nl = 1;
        FILE *file;
        file = fopen("testWords.in", "r");
    
        if (file) {
            printf("%d. ", nl);
            while((c = getc(file)) != EOF) {
                if (p == '\n') {
                    ++nl;
                    printf("%d", nl);
                }
                p = c;
                printf("%c", c);
            }
            fclose(file);
        }
        return 0;
    }