English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C File fputs() and fgets()

C programming uses fputs() and fgets() to write and read strings from the stream. Let's see an example of writing and reading files using fgets() and fputs() functions.

Writing to a file: fputs() function

The fputs() function writes a line of characters to a file. It outputs a string to the stream.

Syntax:

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

#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 a file: fgets() function

The fgets() function reads a line of characters from a file. It retrieves a string from the stream.

Syntax:

char* fgets(char *s, int n, FILE *stream)

#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