Reputation: 309
I'm writing a program for school; it's my first time working with C.
I'm using fgets to read input, but sometimes fgets doesn't block (throwing the program into an infinite loop). To answer everyone's first question, no, I'm not using scanf before hand leaving the extra \n
which would cause this issue. I am using sscanf at one point, but that's in association with fgets so I assume that's not the issue.
There is some code that was given to us dealing with sockets. I've looked through it and can't find the source of the issue. The code isn't included due to length, but I can include it if that helps.
Long story short, is there any reason fgets wouldn't block for input apart from the scanf issue? Any help is appreciated!
EDIT: I should have made this more clear earlier, but in this case I'm using fgets solely for stdin.
Upvotes: 3
Views: 6277
Reputation: 1
I had the same issue. I was using both fget and scanf in the same program. When i changed everything to fget, the issue disappeared.
Changed all the scanf:
printf("[?]Enter a name for saving the file: ");
scanf("%99s", fileName);
To fget:
printf("[?]Enter a name for saving the file: ");
fgets(fileName, sizeof(fileName), stdin);
fileName[strcspn(fileName, "\n")] = '\0';
Upvotes: 0
Reputation: 2427
I know this is an older question but I thought I'd share what I found when I had this issue. Without your code I can't tell if this is the same issue you had but what I found in my own code was that I was using close()
on file descriptors that were set to 0. Being curious I looked up what file descriptor 0 was in the system and low and behold stdin is FD 0 (http://en.wikipedia.org/wiki/File_descriptor). I'm sure there are many ways of resolving this but in my case I used a simple if statement arround my close:
if(fd > 2)
{
close(fd);
}
Upvotes: 0
Reputation: 1
As with most standard functions in C, you'll need to do a little digging around to figure out what's happening. The best place to start is with the function documentation.
From this documentation, we can see that fgets takes three parameters and returns a char*. Asuming the parameters are correct, the function will read from the stream until it reaches a new-line character or the end of file marker. In the case of success, the return code will be a pointer to the str parameter.
The case your probably more interested in, though, is the failure case. On failure, the function returns NULL. To determine how exactly the failure takes place, you need to check the file error indicator and see if it has printed a message. This can be done as follows:
if ( fgets (mystring , 100 , pFile) == NULL )
{
// We handle error here
if (ferror (pFile))
{
printf ("We encountered an error!\n");
perror ("Error message");
}
}
From here, you should be able to determine what is happening. The likely cause is a invalid parameter or a parameter that is not in the format/condition expected.
Upvotes: 0