Home > database >  Print whole line which starts from given letter
Print whole line which starts from given letter

Time:06-08

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;
}

CodePudding user response:

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);

CodePudding user response:

I would not use fscanf to read line of text.

//fi - input file
//fo - output file
int copyLines(FILE *fi, FILE *fo, char c)
{
    char line[256];
    if(fi && fo)
    {
        while(fgets(line, sizeof(line), fi))
        {
            if(*line = c)
                if(fputs(line, fo) == EOF) return EOF;
        }
    }
    return 0;
}

CodePudding user response:

For starters the format string in the call of fscanf is incorrect

while(fscanf(f, "%[^\n]s", buffer)==1)
                      ^^^

At least you should remove the letter s.

Another problem is that after such a call of fscanf the new line character '\n' is not read. So the next call of fscanf reads an empty string.

It is better to use another C function fgtes. But you need to use it with a caution.

In general a string stored in the input file can be greater than the size of the array buffer.

That means that you need to read some strings in the input file using more than one call of fgets. Otherwise the output file will be formed incorrectly.

The loop can look the following way

int success = 1;

do
{
    success = fgets( buffer, sizeof( buffer ), f ) != NULL;
    if ( success )
    {
        int target = *buffer == usr;

        if ( target ) fprintf( f2, "%s", buffer );
        while ( success && !strchr( buffer, '\n' ) )
        { 
            success = fgets( buffer, sizeof( buffer ), f ) != NULL;
            if ( success && target ) fprintf( f2, "%s", buffer );
        }
    }
}  while ( success );
  • Related