Search code examples
cswitch-statementinfinite-loopdo-while

loop running infinite time after calling display function


do
{
    printf("1 :Enter Company Deatils\n");
    printf("2 :Display stoke Deatils\n");
    printf("0 :Exit\n");
    printf("\nEnter num: ");
    scanf("%d", &n);
    switch (n)
    {
        case 1:
            enter();
            break;
        case 2:
            display();
            break;
    }
}
while (n != 0);

When I enter 2 to call display function after that scanf() not taking any input and running loop for infinite time.

void display_d(){
    point c1;
    FILE *fptr;
    fptr = fopen("company_det.txt","r");
    while(fread(&c1,sizeof(point),1,fptr)){
        printf("\n%s %s %d\n",c1.company_name,c1.bla.date,c1.bla.price);
    }
    fclose(stdin);
}

this is my display function


Solution

  • The function display_d() closes stdin. When the function returns, scanf will try to use stdin to read another digit. This is undefined behavior (see answers here).

    You probably meant to close the file instead of stdin.

    Also, the return value of fopen should be checked. It will be NULL if fopen failed to open the file.