fputs and fgets in c programming language with electro4u.net

24 Dec 2022 Balmiki Mandal 0 C Programming

fputs and fgets in C Programming Language

Introduction

In C programming, the fputs and fgets functions play a crucial role in handling file operations. They are part of the standard I/O library and are used to write and read strings from files, respectively.

>> fputs and fgets are two standard library functions in C that are used for performing input/output (I/O) operations on files.

fputs Function

  • Syntax:

     
  • Description:

    • fputs is used to write a string (str) to the specified file (stream).
    • Returns a non-negative valueon success -1 or Error ,and EOF 
  • Usage Example:

    FILE *file;
    file = fopen("example.txt", "w");
    if (file != NULL) {
        fputs("Hello, World!", file);
        fclose(file);
    }

fgets Function

  • Syntax:

  • Description:

    • fgets reads a line from the specified file (stream) and stores it in the string pointed to by str.
    • It stops reading after num-1 characters or when a newline character is encountered, whichever comes first.
    • Returns str on success, and NULL on error or end-of-file.
  • Usage Example:

    FILE *file;
    char buffer[100];
    file = fopen("example.txt", "r");
    if (file != NULL) {
        while (fgets(buffer, sizeof(buffer), file) != NULL) {
            printf("%s", buffer);
        }
        fclose(file);
    }

Conclusion

Both functions are commonly used for file I/O operations in C programming.

The fputs and fgets functions are fundamental tools for handling file operations in C. Understanding their usage is essential for efficient file I/O operations.

Further Reading:

For further information and examples, Please visit[ C-Programming From Scratch to Advanced 2023-2024]


Top Resources

 

For further information and examples, Please visit [C-Programming From Scratch to Advanced 2023-2024]

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.