How To Write An Integer
In this tutorial nosotros will learn to read and write integer numbers in files in C programming language.
We have already learned how to read and write characters in files in C in the previous tutorial. In this tutorial nosotros will comprehend the getw()
and putw()
role to read and write integers in files.
The getw and putw I/O functions
We use the getw()
and putw()
I/O functions to read an integer from a file and write an integer to a file respectively.
Syntax of getw:
int num = getw(fptr);
Where, fptr
is a file pointer.
Syntax of putw:
putw(n, fptr);
Where, due north
is the integer we want to write in a file and fptr
is a file pointer.
Write a program in C to create a new file and save integer numbers entered by user in a file
For this we will first create a FILE
pointer and create a file past the name integers
. You tin can use any other name you like.
Then we volition use the putw()
function to write the integer number in the file. When -1 is entered we stop the reading and shut the file.
Later that nosotros tin can use the getw()
function to read the file information till we hit the EOF (End Of File) character and show it in the panel.
#include <stdio.h> int main(void) { // creating a FILE variable FILE *fptr; // integer variable int num; // open up the file in write mode fptr = fopen("integers", "w"); if (fptr != Goose egg) { printf("File created successfully!\n"); } else { printf("Failed to create the file.\n"); // exit status for Os that an mistake occurred return -1; } // enter integer numbers printf("Enter some integer numbers [Enter -ane to exit]: "); while (i) { scanf("%d", &num); if (num != -1) { putw(num, fptr); } else { suspension; } } // shut connectedness fclose(fptr); // open file for reading fptr = fopen("integers", "r"); // display numbers printf("\nNumbers:\northward"); while ( (num = getw(fptr)) != EOF ) { printf("%d\n", num); } printf("\nEnd of file.\n"); // shut connection fclose(fptr); return 0; }
Output:
File created successfully! Enter some integer numbers [Enter -i to exit]: 10 twenty 30 40 l -1 Numbers: 10 20 xxx 40 l Stop of file.
Following is the content inside the integers
file.
How To Write An Integer,
Source: https://dyclassroom.com/c/c-file-handling-read-and-write-integers
Posted by: myerstoop1998.blogspot.com
0 Response to "How To Write An Integer"
Post a Comment