¤ Home » Programming » C Tutorial » File Handling in C - Part 3 of 7

File Handling in C - Part 3 of 7

String I/O functions - fgets, fputs

C supports string based I/O operations using fgets (for input) and fputs (for output) functions. The behaviours of these two functions are quite similar to the gets and puts functions, discussed earlier. The differences can be seen from the following declaration:

	fgets(<string>, <length>, <file pointer>);
	fputs(<string>, <file pointer>);

Reading a File

The function fgets reads characters including embedded spaces from the file pointed to by the file pointer and stores them in the string, appending a null character to terminate the string. The maximum number of characters read would be equal to length - 1, since one character position is kept aside for null terminator character, viz. \0. If this function encounters a newline character \n or the end of the file EOF before it has read the specified number of characters, viz. length - 1, it returns only the characters read up to that point including the new line character. Thereafter, fgets automatically puts a null terminator at end of the read string.

Note that you can also use the function fscanf to read strings from a file. However, fscanf has a limitation that it stops reading after encountering the first blank space character.

Function fgets returns NULL (a symbolic constant defined in stdio.h with a 0 value), if read attempt fails (may be due to end of file being encountered).


Writing to a File

The function fputs writes the string to the file pointed to by the file pointer. It returns a non-negative value on success, otherwise EOF is returned in case of any error. Note that you can also use function fprintf to write a string into a file.


Example:

To understand the usage of fgets and fputs, we will re-write the file copy program that we wrote earlier. However, this time we will use fgets and fputs instead of fgetc and fputc.

/*
 Program to create a copy of file1.txt as file2.txt
 --------------------------------------------------
*/

#include <stdio.h> 

main()
{
  FILE *fp1, *fp2;
  char line[81];

  fp1 = fopen("file1.txt", "r");
  if(fp1 == NULL)
  {
	puts("Error!! Unable to open file1.txt for reading.");
	return;
  }

  fp2 = fopen("file2.txt", "w");
  if(fp2 == NULL)
  {
	puts("Error!! Unable to create file2.txt.");
	return;
  }

  while(fgets(line,81,fp1) != NULL) fputs(line,fp2);
  fclose(fp1);
  fclose(fp2);
}

Compare the above program with the one written using fgetc and fputc in the previous article.

You can use the following code to view the contents of the newly created file file2.txt.

  FILE *fp;
  char line[81];

  fp = fopen("file2.txt", "r");
  if(fp == NULL)
  {
	puts("Error!! Unable to open file2.txt for reading.");
	return;
  }

  while(fgets(line,81,fp) != NULL) printf("%s\n",line);
  fclose(fp);

Exercises:

1. Identify the errors, if any, in the following program:

  #include<stdio.h>
  main()
  {
	FILE *fp;
	char ch;
	while((ch = getchar()) != EOF)
		fputc(ch,fp);
	fclose(fp);
  }

2. Identify the errors, if any, in the following program:

  #include<stdio.h>
  main()
  {
	FILE *fp1, *fp2;
	char ch;
	fp1 = fopen("in.dat", "w");
	fp2 = fopen("out.dat", "r");
	while((ch = fgetc(fp1)) != EOF)
		fputc(ch,fp2);
	fclose(fp1);
}



Share:




comments powered by Disqus


Web Service Offers

Accounting System for Small Business
5,999 4,999 (16.67% off)
per Year

Ecommerce on the Cloud

An online store hosted on the Cloud. Sell unlimited products. Integrated business functions. Well-suited for high traffic website.

39,999 29,999 (25% off)

Ecommerce Premium

An e-commerce website well-suited for companies having a large portfolio of products. Sell unlimited products. Manage both offline and online sales from one system.

40,000 25,000 (37.5% off)

Ecommerce Business

Launch your online business. Sell up to 5000 products. Collect payment via multiple online and offline payment methods.

35,000 25,000 (28.57% off)

Ecommerce Pro

Get a Mobile friendly online store front. Sell up to 1000 products.

35,000 25,000 (28.57% off)

Ecommerce Starter

Start selling your products online. Scale up as your business grows.

35,000 25,000 (28.57% off)

Website on the Cloud

Custom built, responsive corporate website hosted on the cloud. Mirrored on 3 servers. Includes visitor signup with CRM functions/

19,999 9,999 (50% off)

Website Corporate

Custom built, responsive corporate website with CRM. Our most popular website plan.

19,000 9,000 (52.63% off)

Website Business - 1000 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

18,000 8,000 (55.56% off)

Website Business - 500 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

17,500 7,500 (57.14% off)

Website Business - 100 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

17,000 7,000 (58.82% off)

Website Business - 50 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

16,500 6,500 (60.61% off)

Website Business - 25 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

16,000 6,000 (62.5% off)

Website Starter - 5 Pages

Get started with your own website at most affordable cost.

15,000 5,000 (66.67% off)


Looking to build a website?
Launch a 5 page website in 1 day at only Rs.499/year. Hosting included.





About the Author

Rajeev Kumar
CEO, Computer Solutions
Jamshedpur, India

Rajeev Kumar is the primary author of How2Lab. He is a B.Tech. from IIT Kanpur with several years of experience in IT education and Software development. He has taught a wide spectrum of people including fresh young talents, students of XLRI, industry professionals, and govt. officials.

Rajeev has founded Computer Solutions & WebServicesWorldwide.com, and has hands-on experience of building variety of web applications and portals, that include - SAAS based ERP & e-commerce systems, independent B2B, B2C, Matrimonial & Job portals, and many more.



Copyright © How2Lab.com. All rights reserved.

Refer a friend | Sitemap | Disclaimer | Privacy Policy