Site icon i2tutorials

Reading and Writing String in a file

Reading and Writing String in a file

 

Reading String from a file: fgets( )

 

 

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.

 

 

Writing Or Printing String in a file: fputs( )

 

 

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.

 

 

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:

 

 

 

Exit mobile version