954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem with a programme?

#include<stdio.h>

int main()
{
    FILE *reading;
    FILE *writing;
    int condition,condition2;
    char input[100];
    char save[100];
    
    printf("Type a name to open for reading : ");
    scanf("%s",input);
    
    reading = fopen(input,"r"); /* OPENS the file name we typed above for reading */
    if(reading != NULL)
    {
        do
        {
            condition = fgets(save,30,reading);
            printf("\n%s",save);
        }while(condition != NULL);
    }
    else
    {
        printf("\nFile not found!!!!!\n");
    }
    getchar();
    getchar();
    fclose(reading);
    return(0);
}

in the do while loop the programme picks up 100 characters from the file...
but what if a file is not hundred characters...

then the programme is showing lines 2-3 times for completion of hundred characters...

if a file has 50 characters then the programme will show 50 characters 2 times for completion of 100 characters....
means it will print the programme 2 times....


what to do...
what to do to avoid this ....

lionaneesh
Junior Poster
109 posts since Feb 2010
Reputation Points: 6
Solved Threads: 5
 
do
        {
            condition = fgets(save,30,reading);
            printf("\n%s",save);
        }while(condition != NULL);

When you read the last part of the file, condition is not NULL.

It doesn't become NULL until you try to readafter you've reached the end. Now you have an error. But you output the last stuff read again. Then the loop exits.

You need to figure out how to exit when you get the error, not after.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 
condition = fgets(save,30,reading);

fgets() returns a pointer to a string. condition is an int
declare condition as such: char *condition; save is a buffer of 100, but you only use 29 + the nul terminator '\0'
A better statement would be:

fgets( save, sizeof save, reading );


printf("\n%s",save); does add an extra return to each successful return of fgets() when displaying.

A possible better construct could be:

while ( fgets( save, sizeof save, reading ) != NULL )
    printf( "%s", save );

which will stop the loop if the file is empty or has reached the EOF, preventing printf() to display beyond that failure. And you don't need a variable named condition.

Aia
Nearly a Posting Maven
2,392 posts since Dec 2006
Reputation Points: 2,224
Solved Threads: 218
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: