Getw() and Putw() function in CIntroductionReading and writing data to external files in the C programming language need careful file handling. Two of the functions provided by the standard I/O library to communicate with files are getw() and putw() functions. These routines are important for effectively managing enormous datasets because they can read and write binary data to files. In this article, we will examine getw() and putw() function in-depth, along with code snippets and usage descriptions. The function getw():The getw() function is used to read binary data from a file. A pointer to the file stream from which the data is to be read serves as its sole argument. The file pointer is advanced in accordance with how the function reads the data, which is normally read as an integer (4 bytes). Syntax:It has the following syntax: Example: Using getw() to read dataAssuming we have a binary file called "file.bin" that has a list of integers in it: Code: Output: Let's say the binary data in the "file.bin" file is 10 20 30 40 50. The program's output will be: 10 20 30 40 50 Explanation:
The putw() MethodThe putw() function is used to write binary data to a file. The data to be written and a pointer to the file stream where the data is to be written are its two required inputs. The data is written to the file as an integer, which is normally 4 bytes long. Syntax:It has the following syntax: int putw(int data, FILE *stream); Example: Using putw() to write dataLet's take a program that uses putw() to write a series of integers to a binary file: Code: Output: A binary file named "file.bin" will be produced after running the program. The integers from the data array will be represented in binary form in this file: 10 20 30 40 50. Explanation:
Some important points:
ConclusionIn this article, we examined the C methods getw() and putw() for reading and writing binary data to files. These functions can be helpful when working with huge datasets or maintaining the binary representation of data. Always handle file operations carefully, ensuring files are opened and closed correctly to prevent any problems.
Next Topiclseek() in C
|