fputc() and fgetc()
Writing File : fputc() function
the fputc() function is used to write a single character into file. It outputs a character to a stream. Syntax:
int fputc(int c, FILE *stream)
Example:
#include <stdio.h> main(){ FILE *fp; fp = fopen("file2.txt", "w"); //opening file fputc('b',fp); //writing single character into file fclose(fp); //closing file } file2.txt b
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character from the stream. It returns EOF at the end of file. Syntax:
int fgetc(FILE *stream)
Example:
#include <stdio.h> void main() { FILE *fp; char c; fp=fopen("myfile.txt","r"); while((c=fgetc(fp))!=EOF) { printf("%c",c); } fclose(fp); } myfile.txt this one is general text message
fputs() and fgets()
The fputs() and fgets() in C programming are used to write and read string from stream. Let's see examples of writing and reading file using fgets() and fgets() functions
Writing File : fputs() function
The fputs() function writes a line of characters into file. It outputs string to a stream. Syntax:
int fputs(const char *s, FILE *stream)
Example:
#include <stdio.h> void main() { FILE *fp; fp=fopen("myfile3.txt","w"); fputs("hello c language",fp); fclose(fp); } myfile3.txt hello c language
Reading File : fgets() function
The fgets() function reads a line of characters from file. It gets string from a stream. Syntax:
char* fgets(char *s, int n, FILE *stream)
Example:
#include <stdio.h> void main() { FILE *fp; char text[400]; fp=fopen("myfile3.txt","r"); printf("%s",fgets(text,300,fp)); fclose(fp); } Output: hello c language