
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Explain the functions putw() and getw() in C language
A file is a collection of data stored in secondary memory. Files are used to store information that programs can determine. A file represents a sequence of bytes, Whether it is a text file or a binary file. It is a collection of records or is a location on the hard disk where data is stored permanently.
Operations on Files
The operations on files in the C programming language are as follows ?
- Naming the file
- Opening the file
- Reading from the file
- Writing into the file
- Closing the file
Syntax
The syntax for opening a file is as follows ?
FILE *File pointer;
For example, FILE * fptr;
The syntax for naming a file is as follows ?
File pointer = fopen ("File name", "mode");
For example,
fptr = fopen ("sample.txt", "r"); FILE *fp; fp = fopen ("sample.txt", "w");
The putw() Function
The putw() function is used for writing a number into a file. This function writes binary data to a file. It requires two inputs: the data to be written and a pointer to the file. The syntax for putw() function is as follows ?
putw (int num, FILE *fp);
In the example below, the code writes the integer value to the file pointed to by the putw() function.
FILE *fp; int num; putw(num, fp);
The getw() Function
The getw( ) function is used for reading a number from a file. The syntax for getw() function is as follows ?
int getw (FILE *fp);
Example
The below example reads an integer from the file that is pointed by fp and stores the data in the variable num using getw().
FILE *fp; int num; num = getw(fp);
The logic for writing numbers into a file is as follows ?
fp = fopen ("num.txt", "w"); for (i =1; i<= 10; i++){ putw (i, fp); } fclose (fp);
The logic for reading numbers from a file is as follows ?
fp =fopen ("num.txt", "r"); printf ("file content is
"); for (i =1; i<= 10; i++){ i= getw(fp); printf ("%d",i); printf("
"); } fclose (fp);
Example
Following is the C program to demonstrate the use of putw() and getw() functions. Here we store numbers from 1 to 10 and print them using these functions ?
#include <stdio.h> int main() { FILE *fp; int i; fp = fopen("num.txt", "w"); for (i = 1; i <= 10; i++) { putw(i, fp); } fclose(fp); fp = fopen("num.txt", "r"); printf("file content is
"); for (i = 1; i <= 10; i++) { i = getw(fp); printf("%d", i); printf("
"); } fclose(fp); return 0; }
Output
When the above program is executed, it produces the following result ?
file content is 1 2 3 4 5 6 7 8 9 10