Reading and Writing String in a file
Reading String from a file: fgets( )
- fgets( ) is a predefined file handling function that is used to read a line of text from an existing file opened in read(“r”) mode by fopen( ), which is the same as like gets( )function.
General Format:
char *fgets(char *s, int n,FILE *fp);
Syntax:
fgets(ch_var ,str_length, filepointer);
Example:
char ch[10]; fgets(ch ,20, fp); Where ‘ch’ is a string variable to be written to the file. Where ‘fp’ is a file pointer object and 20 is the string length in a file.
- The function fgets( ) read character from the stream fp into the character array ‘ch’ until a new line character is read, or end-of-file is reached. It then appends the terminating null character after the last character read and returns ‘ch’ if the end-of-file occurs before reading any character an error occurs during input fgets( ) returns NULL.
Writing Or Printing String in a file: fputs( )
- fputs( ) is a predefined file handling function that is used to print a string in a new file opened in write(“w”) mode by fopen( ), which is the same as like puts( ) function.
General Format:
Int fputs(const char *s, FILE *fp);
Syntax:
fputs(ch_var , filepointer);
Example:
char ch[10]=”gitam”; fputs(ch, fp); Where ‘ch’ is a string variable. Where ‘fp’ is a file pointer object.
- The function fputs( ) writes to the stream fp except the terminating null character of string s, it returns EOF if an error occurs during output otherwise it returns a non-negative value.
Example program:
To Write and Read a string in a file.
#include<stdio.h>
main()
{
char name[20];
char name1[20];
FILE *fp;
fp=fopen("dream.txt","w");
puts(“Enter any String\n”);
gets(name);
fputs(name,fp);
fclose(fp);
fp=fopen("dream.txt","r");
fgets(name1,10,fp); /* Here ‘10’ is nothing but String Length, i.e., uptohowputs(“String from file is:\n”);
many characters u want to access from a file. */
puts(name1);
fclose(fp);
}
Output:
