Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Removing trailing newline character from fgets() input

Removing trailing newline character from fgets() input

August 20, 2021 by James Palmer

Perhaps the simplest solution uses one of my favorite little-known functions, strcspn():
buffer[strcspn(buffer, “n”)] = 0;

If you want it to also handle ‘r’ (say, if the stream is binary):
buffer[strcspn(buffer, “rn”)] = 0; // works for LF, CR, CRLF, LFCR, …

The function counts the number of characters until it hits a ‘r’ or a ‘n’ (in other words, it finds the first ‘r’ or ‘n’). If it doesn’t hit anything, it stops at the ‘’ (returning the length of the string).
Note that this works fine even if there is no newline, because strcspn stops at a ‘’. In that case, the entire line is simply replacing ‘’ with ‘’.

The elegant way:
Name[strcspn(Name, “n”)] = 0;

The slightly ugly way:
char *pos;
if ((pos=strchr(Name, ‘n’)) != NULL)
*pos = ‘’;
else
/* input too long for buffer, flag error */

The slightly strange way:
strtok(Name, “n”);

Note that the strtok function doesn’t work as expected if the user enters an empty string (i.e. presses only Enter). It leaves the n character intact.
There are others as well, of course.

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in