Tuesday, January 7, 2014

Reading contents of file using C programming

To read contents of  file C programming offers various data structure to read, write etc. like scanf (), printf(), gets(), puts(), fscanf() etc. In this blog I am using some data structure to read file contents. 

The data structure used in my program to read file are:
    1. printf()  :-This library function provides facility to write contents on console. Ex: printf("This sting is printed on console ") 
    2. scanf()  :-This library function provides facility to reads contents from console. Ex: scanf("%s",word) in this %s is type specifier for string which read input as string.
    3. fopen() :-This library function provides facility to open file specified name as parameters. the parameters of this function are file name and mode to in which file is opened like read, write, append etc. there is other thing required is FILE pointer to hold address returned by this function.       ex: FILE *fp;                                                                         fp=fopen("file","r"); // here file is file to be opened and r specifies read.
    4. feof()  :-This library function provides facility to indicates that end of file. we have to pass pointer as parameter to this function. ex: feof(fp);
    5. fscanf()  :-This library function provides facility to read contents of file word by word. ex: fscanf(fp,"%s",word);   In fp is file pointer and %s specifies string to be read and word is variable which stories contents that to be read.



Ok now look at program:-

#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *f;
char file_name[20],wrd[20];
printf("\nEnter File Name:");
scanf("%s",file_name);
f=fopen(file_name,"r");
while(!feof(f))
{
fscanf(f,"%s",wrd);
printf("\n%s",wrd);
}
printf("\n");
return 0;
}

Output:-

ravikumar@ravikumar:~$ gcc read.c 
ravikumar@ravikumar:~$ ./a.out

Enter File Name:demo.txt

hello
my
name
is
ravikumar
wagh

No comments:

Post a Comment