• C

fget() function to handle variable length user input

How can I write a program that reads a line from standard input and writes it to standard output? The program has to handle user input of variable length, and has to check for and deal with error conditions.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

fgets allows you to read a line of input into a string (with an upper limit in length) :


If you want to account for the possibility that there might be more input than that upper limit, you can always call fgets in a loop until the last character is a newline ('\n') character.

You'll have to of course allocate sufficient memory. The realloc function will probably be useful for increasing the allocated size of the string when needed :


And finally, you can output the string again using fputs :


As you mention : error checking is indeed a good idea, so check whether each function call succeeded by checking their return values. Refer to the reference pages for information on the error cases.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
robo_docAuthor Commented:
How would I check the last character entered and compare it with "/n"? I thought about doing something like a while loop with the condition as the last character entered != \n
>> How would I check the last character entered and compare it with "/n"?

The newline character is '\n' (ie. a backslash).

You can check whether the last character of a string is the newline character simply like this :
size_t len = strlen(str);
if (str[len - 1] == '\n') {
    /* we have a newline character */

Open in new window

Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

robo_docAuthor Commented:
How do I deal with any error given by the realloc function? Is there a try/catch block that I can use like in Java?
>> How do I deal with any error given by the realloc function?

You check if it returns NULL or not. If it returns NULL, it means that the re-allocation failed.

Note that in that case, you need to make sure that you still have a pointer to the original memory, so you don't have a memory leak.

See the code below for an example of how to properly use realloc.

>> Is there a try/catch block that I can use like in Java?

This is C. There is no exception handling in C. Errors are indicated in other ways (via a return value, or a global error value, or otherwise).
char* str = (char*) malloc(32 * sizeof(char));           /* initially allocate memory for 32 char's */
if (str == 0) {
    /* oops : memory allocation failed : handle this !!! */

/* ... */

char* tmp = (char*) realloc(str, 64 * sizeof(char));     /* try to double the allocated size to 64 char's */
if (tmp == 0) {
    /* oops : memory allocation failed : handle this !!! */
else {
    str = tmp;                                           /* success !! So we "commit" the change */

Open in new window

>> The solutions only told me what I already knew with regards to the program methods

I'm sorry, but I find that hard to believe given the two follow-up questions you asked.

>> I did not and could not properly implement it

Then why didn't you ask for further assistance ? A C grade without giving the chance of earning an A, is the best thing you can do if you want to offend the people that are trying to help you.
robo_docAuthor Commented:
I only had until Monday to complete the solution. I knew about the realloc and malloc methods because I read about them in the textbook I have. I did not mean to offend, I just wanted a more specific implementation of the C code.
Are you aware that we are not allowed to solve assignments for you ? The only thing we can do, is guide you into solving the assignment for yourself - we can answer specific questions, post helpful hints, and pointers in the right direction, and that's exactly what I did.

If you need further help, I'll be happy to provide it ...
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.