Suppose I have a program that asks the user for data
#include<stdio.h>int main(){int x, y, z;printf("Enter 3 integers\n");scanf("%d %d %d", &x, &y, &z);}If we run this program, the user will enter data in the command line and hit enter.
To use redirection we need the data in a file.
data.txt
1 23we can run the executable like below
./a.out < data.txtSimilarly, we can redirect the output of any program
./a.out > output.txtboth
./a.out < data.txt >output.txt#include<stdio.h>int main(){int x, y, z;printf("Enter 3 integers\n");FILE * data;data = fopen("data.txt",'r');fscanf(data,"%d %d %d", &x, &y, &z);printf("%d\n%d\n%d\n", x, y, z);data = fclose(data);}fopen() and fclose()
the fopen function is shown below
FILE *fopen(const char *filename, const char *mode)We used it in the code above but what other modes can we use.
'r' - read (used in the above example)'w' - write (creates a file. If file exists, it will be erased.'a' - appends to a file. Writing operations append data at the end of the file. If the file does not exist. It is created.'r+' - opens file to update both reading and writing. The file must already exist. This mode will not create a file'w+' - opens an empty file for both reading and writing.'a+' - opens a file for reading and appending.This can be used in a similar manner to fscanf() but the file must open in one of the write modes listed above. An example is shown below.
#include<stdio.h>int main(){int x, y, z;printf("Enter 3 integers\n");scanf("%d %d %d", &x, &y, &z);FILE * data;data = fopen("new.txt",'w');fprintf(data,"%d\n%d\n%d\n", x, y, z);data = fclose(data);}Consider the following text file abc.txt
NAME AGE CITYabc 12 hyderbadbef 25 delhicce 65 bangalore Now, we want to read only the city field of the above text file, ignoring all the other fields. A combination of fscanf and the trick mentioned above does this with ease
/*c program demonstrating fscanf and its usage*/#include<stdio.h>int main()
{ FILE* ptr = fopen("abc.txt","r"); if (ptr==NULL)
{ printf("no such file."); return 0;
}
/* Assuming that abc.txt has content in below format NAME AGE CITY abc 12 hyderbad bef 25 delhi cce 65 bangalore */ char* buf[100]; while (fscanf(ptr,"%*s %*s %s ",buf)==1)
printf("%s\n", buf);
return 0;
}