13.8. puts(), fputs()

Write a string to the console or to a file.

Prototypes

#include <stdio.h>

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

Description

Both these functions output a NUL-terminated string. puts() outputs to the console, while fputs() allows you to specify the file for output.

Return Value

Both functions return non-negative on success, or EOF on error.

Example

// read strings from the console and save them in a file

#include <stdio.h>

int main(void)
{
    FILE *fp;
    char s[100];

    fp = fopen("datafile.txt", "w"); // error check this!

    while(fgets(s, sizeof(s), stdin) != NULL) { // read a string
        fputs(s, fp);  // write it to the file we opened
    }

    fclose(fp);

    return 0;
}

See Also