| << Prev | Beej's Guide to C | Next >> |
Write a string to the console or to a file.
#include <stdio.h> int puts(const char *s); int fputs(const char *s, FILE *stream);
Both these functions output a NUL-terminated string. puts() outputs to the console, while fputs() allows you to specify the file for output.
Both functions return non-negative on success, or EOF on error.
// 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;
}
| << Prev | Beej's Guide to C | Next >> |