How to Read Integers From a Text File in C++
In this tutorial nosotros will larn 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 we will cover the getw() and putw() role to read and write integers in files.
The getw and putw I/O functions
We apply 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, north is the integer nosotros want to write in a file and fptr is a file pointer.
Write a program in C to create a new file and salve integer numbers entered past user in a file
For this we will beginning create a FILE pointer and create a file past the name integers. You lot can use any other proper name you similar.
Then nosotros will use the putw() office to write the integer number in the file. When -1 is entered we terminate the reading and close the file.
Afterward that we tin can use the getw() part to read the file information till we hit the EOF (End Of File) character and show information technology in the console.
#include <stdio.h> int primary(void) { // creating a FILE variable FILE *fptr; // integer variable int num; // open the file in write style fptr = fopen("integers", "w"); if (fptr != NULL) { printf("File created successfully!\n"); } else { printf("Failed to create the file.\due north"); // leave condition for OS that an error occurred render -one; } // enter integer numbers printf("Enter some integer numbers [Enter -1 to exit]: "); while (i) { scanf("%d", &num); if (num != -ane) { putw(num, fptr); } else { break; } } // close connection fclose(fptr); // open file for reading fptr = fopen("integers", "r"); // display numbers printf("\nNumbers:\n"); while ( (num = getw(fptr)) != EOF ) { printf("%d\n", num); } printf("\nEnd of file.\n"); // close connexion fclose(fptr); render 0; } Output:
File created successfully! Enter some integer numbers [Enter -one to get out]: ten twenty 30 forty l -ane Numbers: 10 xx 30 40 fifty Cease of file. Post-obit is the content inside the integers file.
Source: https://dyclassroom.com/c/c-file-handling-read-and-write-integers
0 Response to "How to Read Integers From a Text File in C++"
Publicar un comentario