A getw() is used to read a number at a time from the specified file. It returns the number that read from the file. It reads the number from the current cursor position and once the character read from the file, cursor will advance (move) to next number. If pointer is at end of file or if an error occurs EOF file is returned by this function.
stream : It is file or stream variable from where we want to read number. If you want to read from console, you can specify stdin.
Write number from file using putw()
Write number from file using putw()
1 #include <stdio.h>
2
3 int main() {
4 FILE *file;
5 int i = 0;
6 file = fopen("text.txt", "w");
7
8 while(i < 10) {
9 putw (i, file);
10 i++;
11 }
12 fclose(file);
13
14 printf("String written to file successfully !");
15 return 0;
16 }
In the above example, first we are writing number using putw() function and same we are reading using getw() function. Once the number read successfully, the cursor will move to next number.
1 String written to file successfully !
Reading file using getw()
Reading file using getw()
1 #include <stdio.h>
2
3 int main() {
4 int num;
5 FILE *file;
6
7
8 file = fopen("text.txt", "r+");
9 do {
10 num = getw(file);
11 if (feof(file))
12 break ;
13 printf("%d ", num);
14
15 } while(1);
16 fclose(file);
17 return 0;
18 }
In the above example, a file is open using fopen() by specifying a name of file and file open mode by specifying a r+. A do while continue reading number until file pointer reach end of file. A read number is assigned to the variable and printed using printf() by using %d format specifier.
Related options for your search