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

6

I know that both functions are for displaying strings on the screen. But what is the difference between them? Which one is best to use?

    
asked by anonymous 12.09.2014 / 18:14

1 answer

12

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

int puts(const char *s);

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

Although it is not common, of course the fputs() can be used to write in console as well, if the stream for the file is the same console that for the operating system does not stop being 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 placed it on GitHub for future reference .

Usually printf() and fprintf() instead of these functions, since they are more powerful in formatting the data. But if you do not need the formatting, something simpler should be used.

    
12.09.2014 / 18:35