Tutorials  /  JavaScript

Comparison of fgets() and gets() in C Programming

Ccentron Redaktion · November 2024 ·3 min read ·JavaScript, Tutorial

Effective management of user inputs is crucial in C programming to develop stable applications. While the commonly used scanf() function is versatile and can handle basic inputs like numbers or single words, it falls short when dealing with strings containing spaces or special characters. Functions like fgets() and gets() offer a much better alternative in such cases.

VM

Try it yourself: cloud servers from €3.12/month

ccloud³ VMs from German data centers – deployed in seconds, billed by the hour, with a €200 starting credit for new accounts. Launch a server →

When we use the scanf() function, it quickly becomes evident that it does not handle strings correctly when spaces are included. Let's look at an example:

C
#include
int main()
{
    char string[10];
    printf("Enter the string: ");
    scanf("%s", string);
    printf("\n %s",string);
    return 0;
}

If you enter Hello World, only Hello is displayed because scanf() stops reading at a space. This is where the functions gets() and fgets() come into play, allowing you to read a complete string.

The gets() Function

The gets() function provides a simple way to read an entire string up to a newline character. Here's how it works:

C
#include
int main()
{
    char string[10];
    printf("Enter the String: ");
    gets(string);
    printf("\n%s",string);
    return 0;
}

If you now enter Hello World, the entire string is correctly displayed, unlike with scanf().

The fgets() Function

The fgets() function, which is also part of the standard C library, is even more flexible. It not only allows you to read a line but also lets you specify the maximum number of characters to be read, ensuring higher security. This prevents issues like buffer overflows that can occur with gets().

The syntax of fgets() is as follows:

Code
fgets(char *str, int n, FILE *stream);

Here:

  • str is the string where the input is stored.
  • n is the maximum number of characters to be read.
  • stream is the input source, such as a file or standard input.

An example of reading from a file using fgets():

C
#include
int main()
{
    char string[20];
    FILE *fp;
    fp = fopen("file.txt", "r");
    fgets(string, 20, fp);
    printf("The string is: %s", string);
    fclose(fp);
    return 0;
}

If the file file.txt contains the line JournalDev fgets() example!, it will be correctly displayed.

Reading from standard input using fgets() is just as straightforward. Here's an example:

C
#include
int main()
{
    char string[20];
    printf("Enter the string: ");
    fgets(string, 20, stdin);  // Input from stdin stream
    printf("\nThe string is: %s", string);
    return 0;
}

Here too, entering Hello World correctly captures the entire string.

Conclusion

In summary, both gets() and fgets() can overcome the limitations of scanf(). However, the fgets() function is much safer as it respects the maximum buffer size and avoids potential memory issues. For this reason, fgets() is highly recommended for use in modern programming.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren