C Language Example - Writing a String to a File

C Language Examples

Write a string to a file.

Example

#include <stdio.h> #include <stdlib.h>/* exit() function */ int main() { char sentence[1000]; FILE *fptr; fptr = fopen("example.txt", "w"); if(fptr == NULL) { printf("Error!"); exit(1); } printf("Input string:\n"); fgets(sentence, (sizeof sentence / sizeof sentence[0]), stdin); fprintf(fptr,"%s", sentence); fclose(fptr); return 0; }

The output result is:

输入字符串:
example.com

Open the file example.txt:

$ cat example.txt 
example.com

C Language Examples

other extensions