What is the difference between puts() and fputs()?

Asked

Viewed 898 times

7

I know both functions are for display strings on screen. But what’s the difference between them? Which one is better to use?

1 answer

12


It’s not a question of being better, it’s a question of where you need the writing done. puts() writes to the console, while fputs() writes through a previously opened file handler. see function statements that make clear the difference.

int puts(const char *s);

int fputs(const char *s, FILE *stream);

Although it is not common, it is clear that the fputs() can be used to write to console as well, if the stream for the file to be the console itself that for the operating system does not cease to be a file.

A simplified example using both:

#include <stdio.h>

int main(void) {
    FILE *fp;
    char s[100];
    fp = fopen("datafile.txt", "w");
    while(fgets(s, sizeof(s), stdin) != NULL) { //o fgets está lendo do console (stdin)
        fputs(s, fp);  // escreve no arquivo
        puts(s); //escreve no console
    }
    fclose(fp);
    return 0;
}

I put in the Github for future reference.

It is customary to use printf() and fprintf() instead of these functions, since they are more powerful in formatting the data. But if you don’t need formatting, something simpler should be used.

  • 3

    Attention to a difference between the two functions: fputs() write down exactly what you send; puts() adds a '\n'.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.