c - fgets and dealing with CTRL+D input -
i grabbing standard input user , if user presses ctrl+d, want display error , terminate program. think perhaps issue may related being stuck in while loop;
int readinput(){ char buff[10]; int count = 0; int counter; printf("enter random number: "); fgets(buff, 10, stdin); if ((int) strtol(buff, null, 10) == 0){ printf("error reading number. \n"); return 0; //this hit if user presses ctrl+d @ input. } counter = atol(buff); while (count < counter){ printf("enter label: "); fgets(buff, 10, stdin); if ((int) strtol(buff, null, 10) == 0){ printf("error reading label"); return 0; //this not hit if user presses ctrl+d @ input, why? //i've tried assigning variable 0, breaking out of loop using break; , returning variable @ end of function not work. //the rest of while loop continues if user hit ctrl+d printf("enter value: " ); fgets(buff, 10, stdin); //..rest of while loop gets other inputs above count++; } //termination happens in main, if readinput returns 0 call return exit_failure; i don't understand why @ first input if user presses ctrl+d, program responds accordingly second time ignores it.
on linux, ctrl + d generates eof, need check return value of fgets() every time. when eof encountered, fgets() returns null pointer
if (fgets(buff, 10, stdin) == null) print_error();
Comments
Post a Comment