fputs() and fgets() in C

C fputs() and fgets()

C 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>

#include<conio.h>

void main(){

FILE *fp;

clrscr();

fp=fopen(“myfile2.txt”,“w”);

fputs(“hello c programming”,fp);

fclose(fp);

getch();

}

myfile2.txt

hello c programming

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>

#include<conio.h>

void main(){

FILE *fp;

char text[300];

clrscr();

fp=fopen(“myfile2.txt”,“r”);

printf(“%s”,fgets(text,200,fp));

fclose(fp);

getch();

}

Output:

hello C programming

 

Related Post:

Features of C Programming Language

Variables in C

Data Types in C

Keywords in C

C Operators

Comments in C

Escape Sequence in C

C Functions

Storage Classes in C

Dynamic memory allocation in C

Factorial Program in C

Leap year program in C

Fibonacci Series in C

Prime Number program in C

Palindrome program in C

Sum of digits program in C

Escape Sequence in C

ASCII value in C

Difference Between Type Casting and Type Conversion in C

Difference Between Variables and Constants

Matrix multiplication in C

C Program to generate Fibonacci Triangle

C Program to print “hello” without semicolon

C Program to swap two numbers without third variable

C Program to reverse number

Count the number of digits in C

Tokens in C

C Identifiers

C Strings

Compile time vs Runtime in C

C break statement

C goto statement

Type Casting in C

C String Functions

C Pointers

Dangling Pointers in C

void pointer in C

Pointer to Pointer in C

Recursion in C

Call by value and Call by reference in C

File Handling in C

C fprintf() and fscanf()

C fputc() and fgetc()

C fseek() function

Constant Pointers in C