The Ultimate Guide to Working on Files with Strings

Files with strings

To store a string into a file, we can use fputs() function. Similarly to read a string from a file we can use fgets() function. Both functions are defined in <stdio.h>.

Program to store data in the form of strings into a text file.

#include<stdio.h>
#include<string.h>
void main()
{
  char str[80];
  char fname[15];
  FILE *fp;
  printf("\nEnter a filename:");
  gets(fname);
  fp = fopen(fname, "w");
  printf("\n Enter strings:");
  printf("\n Press <Enter< to quit ");
  do{
  gets(str);
  strcat(str, "\n");
  fputs(str,fp);
  }while(*str != '\n');
  fclose(fp);
   }

Output:

Enter a filename: names.txt
Enter strings:
Press <Enter> to quit.
Neha
Parth
Aryan

In above program, we accept a string the keyboard as:

gets(str);

We store the string into the file, using fputs() function as

fputs(str, fp);

Program to read strings from text file and display them.

#include<stdio.h>
#include<string.h>
void main()
{
  char str[80];
  char fname[15];
  FILE *fp;
  printf("\nEnter filename:");
  gets(fname);
  fp = fopen(fname, "r");
  if(fp == NULL)
  {
     printf("\nFile not found");
     return;
  }
  printf("\nThe file contents:");
  while(fgets(str, 80, fp)) != NULL)
  puts(str);
  fclose(fp);
}

Output:

Enter filename: names.txt
The file contents:
Neha
parth
Aryan
Naveed Tawargeri
 

Hi, I'm Naveed Tawargeri, and I'm the owner and creator of this blog. I'm a Software Developer with a passion for Programming.