Search code examples
cloopsfilec-strings

Print whole line which starts from given letter


I'm trying to print lines which starts from given letter to second file but it prints only 1 line and then stops, even if there are more lines which starts with given letter. How to fix it ?

#include <stdio.h>
#include <string.h>
int main()
{
    FILE* f = fopen("story.txt","r");
    char usr;
    printf("enter letter: ");
    scanf(" %c",&usr);

    FILE* f2=fopen("letter.txt","a+");

    char buffer[255];
       while(fscanf(f, "%[^\n]s", buffer)==1)
        if (*buffer == usr)
          fprintf(f2, "%s\n", buffer);

    return 0;
}

Solution

  • The second time through the loop, fscanf(f, "%[^\n]s", buffer) fails to scan anything because the previous call left the \n character in the buffer. This can't get past that.

    Use fgets() instead of fscanf() to read a whole line.

        char buffer[255];
        while(fgets(buffer, sizeof buffer, f))
            if (buffer[0] == usr)
                fprintf(f2, "%s", buffer);