A file is a repository of data that is stored in a permanent storage media, mainly in secondary memory. In order to use the files we should learn how to read information from a file and how to write information into a file.
A very important concept in C is the stream.The stream is a common logical interface to the various devices( files).A stream is linked to a file while using an open operation. A stream is disassociated from a file while using a close operation. The current location, also referred to as the current position, is the location in a file where the next file access will occur.There are two types of streams text and binary.
The following are some difference between text and binary files
- Text file is human readable because everything is stored in terms of text. In binary file everything is written in terms of 0 and 1, therefore binary file is not human readable.
- A newline(\n) character is converted into the carriage return-linefeed combination before being written to the disk. In binary file, these conversions will not take place.
- In text file, a special character, whose ASCII value is 26, is inserted after the last character in the file to mark the end of file. There is no such special character present in the binary mode files to mark the end of file.
- In text file, the text and characters are stored one character per byte. For example, the integer value 1245 will occupy 2 bytes in memory but it will occupy 5 bytes in text file. In binary file, the integer value 1245 will occupy 2 bytes in memory as well as in file.
Binary file always needs a matching software to read or write it.(MP3 player Image Viewer)
Using files in C
There are four steps in using files
- Declare a file pointer variable
- Open a file using fopen() function
- Process the file using suitable functions
- Close the file using fclose() function
To access any file, we need to declare a pointer to FILE structure and then associate it with the particular file. This pointer is referred to as file pointer.
Syntax for declaring file pointer
FILE * fp;
A pointer to FILE structure contains information, such as
size, current file position, type of file etc., to perform operation on
the file.Opening a file function
Open a file using fopen() function
The fopen() function takes two arguments, the name of the
file and the mode in which the file is to be opened. Mode specify the purpose
of opening the file i.e, whether for reading or writing.
Syntax for opening the file in C
fp =
fopen(char *filename,char *mode);
When fopen() function opens a file in memory, it returns a
pointer to this particular file.If fopen() function can't open the file then
it will return NULL.
Example for opening a text file for reading in C
void main()
{
FILE *fp;
fp = fopen("file1.txt","r"); //statement 1
if(fp == NULL)
{
printf("\nCan't open
file or file doesn't exist.");
exit(0);
}
In the above example, statement 1 will open an existing text file "file1.txt" in
read mode and return a pointer to file. If file will not open, an appropriate
message will be displayed.
File opening modes
Mode
|
Meaning
|
r
|
Open a text file for reading
|
w
|
Create a text file for writing
|
a
|
Append to a text file
|
rb
|
Open a binary file for reading
|
wb
|
Open a binary file for writing
|
ab
|
Append to a binary file
|
r+
|
Open a text file for read/write
|
w+
|
Create a text file for
read/write
|
a+
|
Append or create a text file for read/write
|
r+b
|
Open a binary file for read/write
|
w+b
|
Create a binary file for read/write
|
a+b
|
Append a binary file for read/write
|
Note: The complete path of the file must be specified, if
the file is not in the current directory. Most of the functions prototype for
file handling is mentioned in stdio.h.
Close the file using fclose() function
When the
reading or writing of a file is finished, the file should be closed properly
using fclose() function. The fclose() function does the following tasks:
Flushes any
unwritten data from memory.
Discards any
unread buffered input.
Frees any
automatically allocated buffer
Finally,
close the file.
Syntax for
closing the file in C
int fclose( FILE* );
Example for
closing the file in C
void main()
{
FILE *fp;
fp =
fopen("file1.txt","r");
if(fp == NULL)
{
printf("\nCan't open
file or file doesn't exist.");
exit(0);
}
- - - - - - - - - -
- - - - - - - - - -
fclose(fp);
}
Note: A
stream’s buffer can be flushed without closing it by using the fflush() library function.The flushall() command flush all open
streams.pointer
As long as your program is running, if you keep opening files without
closing them, the most likely result is that you will run out of file
descriptors/handles available for your process, and attempting to open
more files will fail eventually. On Windows, this can also prevent
other processes from opening or deleting the files you have open, since
by default, files are opened in an exclusive sharing mode that prevents
other processes from opening them.
Once your program exits, the operating system will clean up after
you. It will close any files you left open when it terminates your
process, and perform any other cleanup that is necessary (e.g. if a file
was marked delete-on-close, it will delete the file then; note that
that sort of thing is platform-specific).
However, another issue to be careful of is buffered data. Most file streams buffer data in memory before writing it out to disk. If you're using
FILE*
streams from the stdio library, then there are two possibilities:Your program exited normally, either by calling the exit(3) function, or by returning from main (which implicitly calls exit(3)).
Your program exited abnormally; this can be via calling abort(3) or _Exit(3), dying from a signal/exception, etc.
If your program exited normally, the C runtime will take care of
flushing any buffered streams that were open. So, if you had buffered
data written to a
FILE*
that wasn't flushed, it will be flushed on normal exit.
Conversely, if your program exited abnormally, any buffered data will not
be flushed. The OS no idea there's some random data lying somewhere in memory that the
program intended to write to disk but did not. So be careful about
that.
Working with Text files
The
following functions provides facility for reading and writing files
Reading
|
Writing
|
fgetc()
|
fputc()
|
fgets()
|
fputs()
|
fscanf()
|
fprintf()
|
fread()
|
fwrite()
|
Character Input and Output
Characters
or a line (sequence of characters terminated by a newline) can be written or
read from a file using following functions.
putc() / fputc() function
The library
function putc() writes a single character to a specified stream.Its prototype is
int putc(int
ch,FILE *fp);
Eg:
char c=’x’;
FILE
*fp=fopen(“abc.txt”,”w”);
putc(c,fp);
// fputc(c,fp) // char x is written to file abc.txt.
fputs() function
To write a
line of characters to a stream, the library function fputs() is used.Its
prototype is
char
fputs(char *str,FILE *fp);
Eg:
char
str[]=”cek”;
FILE
*fp=fopen(“abc.txt”,”w”);
fputs(str,fp);
// string cek is written into file abc.txt
getc() / fgetc() function
The function
getc() and fgetc() are identical and can be used interchangeably. They input a
single character from a specified stream.Its prototype is
int
getc(FILE *fp);
Eg:
FILE
*fp=fopen(“abc.txt”,”r”);
int c;
c=fgetc(fp);
// reads a character
fgets() function
fgets() is a
line oriented function for reading from a file.Its prototype is
char
*fgets(char *str,int n, FILE *fp);
Eg:
FILE
*fp=fopen(“abc.txt”,”r”);
char
line[60];
char *c;
c=fgets(line,60,fp);
The other
two file handling functions to be covered are fprintf() and fscanf().These
functions operate exactly like printf() and scanf() except that they work with
files.
Their prototypes are
int fprintf(FILE
*fp, const char *control-string,…);
int fscanf(FILE
*fp, const char *control-string,…);
Eg:
FILE *fp=fopen("abc.txt","w"); fprintf(fp,”%s”,”cek”);
FILE *fp=fopen("abc.txt","r");int n;
fscanf(fp,"%d",&n);
putw() and getw() function
The putw() function is used to write integers to the file.
Syntax of putw() function
The putw() function is used to write integers to the file.
Syntax of putw() function
putw(int number, FILE *fp);
The putw() function takes two arguments, first is an integer value to be written to the file and second is the file pointer where the number will be written.
eg:putw(n,fp)The getw() function is used to read integer value form the file.
Syntax of getw() function
int getw(FILE *fp);
Eg:
while((num = getw(fp))!=EOF)
printf("\n%d",num);
Binary Files and Direct File I/O
The
operations performed on binary files are similar to text files since both types
of files can essentially be considered as stream of bytes. In fact the same
functions are used to access files in C. When a file is opened, it must be
designated as text or binary and usually this is the only indication of the
type of file being processed.
Direct I/O is used only with binary-mode files. With direct output,
blocks of data are written from memory to disk and in direct input block of
data are read from disk to memory.For
example, a single direct-output function can write an entire array to disk and
a single direct input function call can read the entire array from disk back to
memory.
The C file
system includes two important functions for direct I/O: fread() and fwrite().Their
prototypes are
size_t
fread(void *buffer, size_t size,size_t num,FILE *fp)
size_t
fwrite(void *buffer, size_t size,size_t num,FILE *fp)
The fread() function reads from the file associated with fp, num
number of objects, each object size in bytes, into buffer pointed to by buffer.fwrite() function is the opposite
of fread().It writes to files associated with fp,num number of objects, each object size in bytes, from the
buffer pointed to by buffer.
Sample Programs
Read and display a file character by
character using getc/fgetc function
#include
<stdio.h>
#include
<stdlib.h>
int main()
{
FILE *fp;
int ch;
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
while((ch=getc(fp))!=EOF) // can use ch=fgetc(fp) also
{
putchar(ch);
}
fclose(fp);
}
vowels consonants digits and special characters in a file ( university question)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch,vowels=0,consonants=0,digits=0,specc=0,c=0;
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
while((ch=fgetc(fp))!=EOF)
{
if(ch=='a' || ch=='e' || ch=='i' ||
ch=='o' || ch=='u' || ch=='A' ||
ch=='E' || ch=='I' || ch=='O' ||
ch=='U')
{
++vowels;
}
else if((ch>='a'&& ch<='z') || (ch>='A'&& ch<='Z'))
{
++consonants;
}
else if(ch>='0' && ch<='9')
{
++digits;
}
else if (ch ==' ' || ch =='\n')
{
++specc;
}
c++;
}
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nSpecial characters: %d\n", c-specc-vowels-consonants-digits);
fclose(fp);
}
Reading line by line from a file using fgets
vowels consonants digits and special characters in a file ( university question)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch,vowels=0,consonants=0,digits=0,specc=0,c=0;
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
while((ch=fgetc(fp))!=EOF)
{
if(ch=='a' || ch=='e' || ch=='i' ||
ch=='o' || ch=='u' || ch=='A' ||
ch=='E' || ch=='I' || ch=='O' ||
ch=='U')
{
++vowels;
}
else if((ch>='a'&& ch<='z') || (ch>='A'&& ch<='Z'))
{
++consonants;
}
else if(ch>='0' && ch<='9')
{
++digits;
}
else if (ch ==' ' || ch =='\n')
{
++specc;
}
c++;
}
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nSpecial characters: %d\n", c-specc-vowels-consonants-digits);
fclose(fp);
}
Reading line by line from a file using fgets
#include
<stdio.h>
#include
<stdlib.h>
int main()
{
FILE *fp;
char * ch;
char
line[80];
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
while((fgets(line,80,fp)!=NULL)
{
printf("%s",line);
}
fclose(fp);
}
Reading word by word using fscanf
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char t[100];
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening source file..");
exit(1);
}
while(fscanf(fp,"%s",t)==1)
{
printf("%s\n",t);
}
fclose(fp);
}
Write data to the file( char by char using putc/fputc function)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;
fp=fopen("a.txt","w");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
do{
ch=getchar();
if (ch=='$') break;
putc(ch,fp); //fputc(ch,fp);
}
while(1);
fclose(fp);
}
Write data to the file( as strings using fputs function)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
char t[80];
fp=fopen("a.txt","w");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
printf("Enter strings...type end to stop\n");
do{
fgets(t,80,stdin);
printf("%s\n",t);
if(strcmp(t,"end\n")==0 ) break;
fputs(t,fp);
}
while(1);
fclose(fp);
}
C Program to delete a specific line from a text file
#include <stdio.h>
Reading word by word using fscanf
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char t[100];
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening source file..");
exit(1);
}
while(fscanf(fp,"%s",t)==1)
{
printf("%s\n",t);
}
fclose(fp);
}
Write data to the file( char by char using putc/fputc function)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int ch;
fp=fopen("a.txt","w");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
do{
ch=getchar();
if (ch=='$') break;
putc(ch,fp); //fputc(ch,fp);
}
while(1);
fclose(fp);
}
Write data to the file( as strings using fputs function)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
char t[80];
fp=fopen("a.txt","w");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
printf("Enter strings...type end to stop\n");
do{
fgets(t,80,stdin);
printf("%s\n",t);
if(strcmp(t,"end\n")==0 ) break;
fputs(t,fp);
}
while(1);
fclose(fp);
}
C Program to delete a specific line from a text file
#include <stdio.h>
int main()
{ FILE *fp1, *fp2; //consider 40 character string to store filename
char filename[40];
char c; int del_line, temp = 1;
//asks user for file name
printf("Enter file name: ");
//receives file name from user and stores in 'filename'
scanf("%s", filename);
//open file in read mode
fp1 = fopen(filename, "r");
c = getc(fp1); //until the last character of file is obtained
while (c != EOF)
{ printf("%c", c); //print current character and read next character
c = getc(fp1);
}
//rewind
rewind(fp1);
printf(" \n Enter line number of the line to be deleted:");
//accept number from user.
scanf("%d", &del_line);
//open new file in write mode
fp2 = fopen("copy.c", "w");
c = getc(fp1);
while (c != EOF)
{ c = getc(fp1);
if (c == '\n') temp++; //except the line to be deleted
if (temp != del_line) { //copy all lines in file copy.c putc(c, fp2); } } //close both the files. fclose(fp1);
fclose(fp2);
//remove original file
remove(filename);
//rename the file copy.c to original name
rename("copy.c", filename);
printf("\n The contents of file after being modified are as follows:\n");
fp1 = fopen(filename, "r");
c = getc(fp1);
while (c != EOF)
{ printf("%c", c);
c = getc(fp1);
}
fclose(fp1); return 0;
}
Write data to the file( as strings using fprintf)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp=fopen("a.txt","w");
if (fp==NULL)
{
printf("error opening file..\n");
exit(1);
}
else
{
fprintf(fp,"%s","Welcome\n");
fprintf(fp,"%s","to file handling in C\n");
}
fclose(fp);
}
Write data to the file( as strings using fprintf)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp=fopen("a.txt","w");
if (fp==NULL)
{
printf("error opening file..\n");
exit(1);
}
else
{
fprintf(fp,"%s","Welcome\n");
fprintf(fp,"%s","to file handling in C\n");
}
fclose(fp);
}
Counting number of lines, characters and
words in a file
#include
<stdio.h>
#include
<stdlib.h>
int main()
{
FILE *fp;
int ch;
int
nl=0,nc=0,nw=0;
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
ch=getc(fp);
while(ch!=EOF)
{
if
(ch=='\n') nl++;
if(ch==' ')
nw++;
nc++;
ch=getc(fp);
}
fclose(fp);
printf("Number
of lines=%d, Number of characters = %d,Number of words=%d\n",nl,nc,nw+nl);
}
Cheking whether two files are identical or
different
#include
<stdio.h>
#include
<stdlib.h>
int main()
{
FILE
*fp1,*fp2;
int ca,cb;
char
fname1[50],fname2[50];
printf("Enter
the first file name...\n");
scanf("%s",fname1);
printf("Enter
the second file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"r");
if(fp1==NULL)
{
printf("Error opening file1..");
exit(1);
}
else
if(fp2==NULL)
{
printf("Error opening file2..");
exit(1);
}
else
{
ca=getc(fp1);
cb=getc(fp2);
while(ca!=EOF
&& cb!=EOF && ca==cb)
{
ca=getc(fp1);
cb=getc(fp2);
}
fclose(fp1);
fclose(fp2);
if(ca==cb)
printf("Files
are identical\n");
else if
(ca!=cb)
printf("Files
are different \n");
}
}
Copy one file to another character by
character using getc and putc function( you can also use fgetc and fputc)
#include
<stdio.h>
#include
<stdlib.h>
int main()
{
FILE
*fp1,*fp2;
int ch;
char
fname1[50],fname2[50];
printf("Enter
the source file name...\n");
scanf("%s",fname1);
printf("Enter
the destination file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"w");
if(fp1==NULL)
{
printf("Error opening source
file..");
exit(1);
}
else
if(fp2==NULL)
{
printf("Error opening destination
file..");
exit(1);
}
else
{
while((ch=fgetc(fp1))!=EOF){
fputc(ch,fp2);
}
}
fclose(fp1);
fclose(fp2);
printf("Files
succesfully copied\n");
}
}
Copy one file to another after replacing lower case letters with corresponding uppercase letters.(university question)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2;
int ch;
char fname1[50],fname2[50];
printf("Enter the source file name...\n");
scanf("%s",fname1);
printf("Enter the destination file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"w");
if(fp1==NULL)
{
printf("Error opening source file..");
exit(1);
}
else if(fp2==NULL)
{
printf("Error opening destination file..");
exit(1);
}
else
{
while((ch=fgetc(fp1))!=EOF)
{
if(islower(ch)) ch=toupper(ch);
Copy one file to another after replacing lower case letters with corresponding uppercase letters.(university question)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2;
int ch;
char fname1[50],fname2[50];
printf("Enter the source file name...\n");
scanf("%s",fname1);
printf("Enter the destination file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"w");
if(fp1==NULL)
{
printf("Error opening source file..");
exit(1);
}
else if(fp2==NULL)
{
printf("Error opening destination file..");
exit(1);
}
else
{
while((ch=fgetc(fp1))!=EOF)
{
if(islower(ch)) ch=toupper(ch);
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
printf("Files succesfully copied\n");
}
}
}
fclose(fp1);
fclose(fp2);
printf("Files succesfully copied\n");
}
}
Write a C program to replace vowels in a text file with character ‘x’.(university question)
#include <stdio.h>
#include <stdlib.h>
int isvowel(char ch)
{
ch=tolower(ch);
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return 1;
}
return 0;
}
int main()
{
FILE *fp1,*fp2;
int ch;
char fname1[50],fname2[50];
fp1=fopen("vow.dat","r");
fp2=fopen("x.dat","w");
if(fp1==NULL)
{
printf("Error opening source file..");
exit(1);
}
else if(fp2==NULL)
{
printf("Error opening destination file..");
exit(1);
}
else
{
while((ch=fgetc(fp1))!=EOF)
{
if(isvowel(ch)) ch='x';
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
//remove the original file
remove("vow.dat");
//rename the file temp file x.dat to original name
rename("x.dat", "vow.dat");
printf("Files successfully copied\n");
}
}
Copy one file to another line by line using
fgets and fputs function
#include
<stdio.h>
#include
<stdlib.h>
int main()
{
FILE
*fp1,*fp2;
int ch;
char
fname1[50],fname2[50],t[80];
printf("Enter
the source file name...\n");
scanf("%s",fname1);
printf("Enter
the destination file name...\n");
scanf("%s",fname2);
fp1=fopen(fname1,"r");
fp2=fopen(fname2,"w");
if(fp1==NULL)
{
printf("Error opening source
file..");
exit(1);
}
else
if(fp2==NULL)
{
printf("Error opening destination
file..");
exit(1);
}
else
{
while((fgets(t,sizeof(t),fp1)!=NULL))
{
fputs(t,fp2);
}
fclose(fp1);
fclose(fp2);
printf("Files
succesfully copied\n");
}
}
Merging the contents of two files into a third file(university question)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2,*fp3;
char t[100];
fp1=fopen("first.txt","r");
fp2=fopen("second.txt","r");
fp3=fopen("third.txt","w");
if(fp1==NULL||fp2==NULL)
{
printf("Error opening source file..");
exit(1);
}
else if(fp3==NULL)
{
printf("Error opening destination file..");
exit(1);
}
else
{
while((fgets(t,sizeof(t),fp1)!=NULL))
{
fputs(t,fp3);
}
while((fgets(t,sizeof(t),fp2)!=NULL))
{
fputs(t,fp3);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
printf("Files succesfully merged\n");
}
}
Merging the contents of two files into a third file(university question)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1,*fp2,*fp3;
char t[100];
fp1=fopen("first.txt","r");
fp2=fopen("second.txt","r");
fp3=fopen("third.txt","w");
if(fp1==NULL||fp2==NULL)
{
printf("Error opening source file..");
exit(1);
}
else if(fp3==NULL)
{
printf("Error opening destination file..");
exit(1);
}
else
{
while((fgets(t,sizeof(t),fp1)!=NULL))
{
fputs(t,fp3);
}
while((fgets(t,sizeof(t),fp2)!=NULL))
{
fputs(t,fp3);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
printf("Files succesfully merged\n");
}
}
Reading numbers from a file and separating
even and odd numbers into two different files
#include
<stdio.h>
#include
<stdlib.h>
int main()
{
FILE
*fp,*fpe,*fpo;
int n;
fp=fopen("num.dat","r");
fpe=fopen("enum.dat","w");
fpo=fopen("onum.dat","w");
if
(fp==NULL||fpe==NULL||fpo==NULL)
{
printf("error opening file..\n");
exit(1);
}
else
{
while(fscanf(fp,"%d",&n)==1)
{
if (
n%2==0)
fprintf(fpe,"%d\n",n);
else
fprintf(fpo,"%d\n",n);
}
fclose(fp);
fclose(fpe);
fclose(fpo);
}
}
Note: this program can also be written using putw() getw() function
Note: this program can also be written using putw() getw() function
Write Palindrome words from a file to a new file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int palindrome(char str[50])
{
int i,j;
for(i=0,j=strlen(str)-1;i<j;i++,j--)
if(str[i]!=str[j]) return 0;
return 1;
}
int main()
{
FILE *fp1,*fp2;
char word[50];
fp1=fopen("words.txt","r");
fp2=fopen("palwords.txt","w");
while((fscanf(fp1,"%s",word))!=EOF)
{
if(palindrome(word)) fprintf(fp2,"%s\n",word);
}
fclose(fp1);
fclose(fp2);
}
#include <stdlib.h>
#include <string.h>
int palindrome(char str[50])
{
int i,j;
for(i=0,j=strlen(str)-1;i<j;i++,j--)
if(str[i]!=str[j]) return 0;
return 1;
}
int main()
{
FILE *fp1,*fp2;
char word[50];
fp1=fopen("words.txt","r");
fp2=fopen("palwords.txt","w");
while((fscanf(fp1,"%s",word))!=EOF)
{
if(palindrome(word)) fprintf(fp2,"%s\n",word);
}
fclose(fp1);
fclose(fp2);
}
Reading
an array and writing to a file using fwrite and reading the file using fread
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main()
{
int i,a[SIZE],b[SIZE];
FILE *fp;
printf("Enter 10 elements in
array a...\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
fp=fopen("num.dat","w");
if(fp==NULL)
{
printf("error opening file..\n");
exit(1);
}
fwrite(a,sizeof(int),SIZE,fp);
fclose(fp);
/*opening the file and reading to
array b*/
fp=fopen("num.dat","r");
if(fp==NULL)
{
printf("error opening file..\n");
exit(1);
}
fread(b,sizeof(int),SIZE,fp);
printf("array b is...\n");
for(i=0;i<10;i++)
printf("%d\n",b[i]);
fclose(fp);
}
Program for writing struct to file using fwrite
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
Program for writing struct to file using fwrite
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
{
int
id;
char
fname[20];
char
lname[20];
};
int main ()
{
FILE
*outfile;
//
open file for writing
outfile
= fopen ("person.dat", "w");
if
(outfile == NULL)
{
fprintf(stderr,
"\nError opend file\n");
exit
(1);
}
struct
person input1 = {1, "rohit", "sharma"};
struct
person input2 = {2, "mahendra", "dhoni"};
//
write struct to file
fwrite
(&input1, sizeof(struct person), 1, outfile);
fwrite
(&input2, sizeof(struct person), 1, outfile);
if(fwrite != 0)
printf("contents
to file written successfully !\n");
else
printf("error
writing file !\n");
return 0;
}
Write a C program to create a file and store information about a person, in terms of his name, age and salary.(university question)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
{
char name[50];
int age;
int salary;
};
int main ()
{
FILE *outfile;
// open file for writing
outfile = fopen ("person.dat", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
struct person input1 = {"rohit",45,20000};
struct person input2 = {"mahendra",25,15000};
// write struct to file
fwrite (&input1, sizeof(struct person), 1, outfile);
fwrite (&input2, sizeof(struct person), 1, outfile);
if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");
return 0;
}
Write a C program to create a file and store information about a person, in terms of his name, age and salary.(university question)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
{
char name[50];
int age;
int salary;
};
int main ()
{
FILE *outfile;
// open file for writing
outfile = fopen ("person.dat", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
struct person input1 = {"rohit",45,20000};
struct person input2 = {"mahendra",25,15000};
// write struct to file
fwrite (&input1, sizeof(struct person), 1, outfile);
fwrite (&input2, sizeof(struct person), 1, outfile);
if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");
return 0;
}
Program for reading struct using fread
This program will read the file person.dat file
in the previous program.
#include
<stdio.h>
#include
<stdlib.h>
//
struct person with 3 fields
struct person
{
int
id;
char
fname[20];
char
lname[20];
};
int main ()
{
FILE
*infile;
struct
person input;
//
Open person.dat for reading
infile
= fopen ("person.dat", "r");
if
(infile == NULL)
{
fprintf(stderr,
"\nError opening file\n");
exit
(1);
}
//
read file contents till end of file
while(fread(&input,
sizeof(struct person), 1, infile))
printf
("id = %d name = %s %s\n", input.id,
input.fname,
input.lname);
return
0;
}
There is no need to read each record sequentially, if we want to access a particular record. C supports these functions for random access file processing.
fseek()
ftell()
rewind()
This function is used for seeking the pointer position in the file at the specified byte.
Syntax:
fseek(FILE
*fp,long offset,int position)
Where
fp-file pointer ---- It is the pointer which points to the file.
offset -displacement ---- It is positive or negative.This is the number of bytes which are skipped backward (if negative) or forward( if positive) from the current position.This is attached with L because this is a long integer.
Pointer position:
This sets the pointer position in the file.
fp-file pointer ---- It is the pointer which points to the file.
offset -displacement ---- It is positive or negative.This is the number of bytes which are skipped backward (if negative) or forward( if positive) from the current position.This is attached with L because this is a long integer.
Pointer position:
This sets the pointer position in the file.
Value Pointer position
0 Beginning
of file.
1 Current
position
2 End
of file
Ex:
1) fseek(
p,10L,0)
0 means pointer position is on beginning of the file,from this statement pointer position is skipped 10 bytes from the beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer position is skipped 5 bytes forward from the current position.
3)fseek(p,-5L,1)
0 means pointer position is on beginning of the file,from this statement pointer position is skipped 10 bytes from the beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer position is skipped 5 bytes forward from the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the current
position.
ftell()
This function returns the value of the current pointer position in the file.The value is count from the beginning of the file.
Syntax: long ftell(FILE *fptr);
Where fptr is a file pointer.
Where fptr is a file pointer.
rewind()
This function is used to move the file pointer to the beginning of the given file.
Syntax:
void rewind(FILE *fptr);
Where fptr is a file pointer.
Example program for fseek():
Example program for fseek():
Write a program to read last ‘n’ characters of the file using appropriate file
functions(Here we need fseek() and fgetc()).
#include<stdio.h>
|
||||||||||||||||||||
#include<conio.h>
|
||||||||||||||||||||
void main()
|
||||||||||||||||||||
{
|
||||||||||||||||||||
FILE *fp;
|
||||||||||||||||||||
char ch;
|
||||||||||||||||||||
clrscr();
|
||||||||||||||||||||
fp=fopen("file1.c", "r");
|
||||||||||||||||||||
if(fp==NULL)
|
||||||||||||||||||||
printf("file
cannot be opened");
|
||||||||||||||||||||
else
|
||||||||||||||||||||
{
|
||||||||||||||||||||
printf("Enter
value of n to read last ‘n’ characters");
|
||||||||||||||||||||
scanf("%d",&n);
|
||||||||||||||||||||
fseek(fp,-n,2);
|
||||||||||||||||||||
while((ch=fgetc(fp))!=EOF)
|
||||||||||||||||||||
{
|
||||||||||||||||||||
printf("%c\t",ch);
|
||||||||||||||||||||
}
|
||||||||||||||||||||
}
|
||||||||||||||||||||
fclose(fp);
|
1.Create a file and perform the following
i) Write data to the file
ii) Read the data in a given file & display the file content on console
iii) append new data and display on console
2.Open a text input file and count number of characters, words and lines in it; and store the results
in an output file.
3.Copy one file to another.
4.Merge the content of two files and copy to the other.
5.Read numbers from a file and separate even and odd numbers into two different files.
6.Create a structure employee with fields empid,name and salary.Write the structure into a file.
Read and display employee details from the file ( use fread and fwrite)
7.Write an integer array into a file.Read and display the array elements in reverse order.
8.Read last n characters from a file.
9.Find the palindrome words from a file and write it into a new file.
This comment has been removed by the author.
ReplyDeleteI'm trying to learn more knowledge and your articles are so useful for me. I can understand them easily. They aren't science rocket. I even can apply them in ordinary life. I'm grateful for your sharing. I hope you will write often and post more articles. email-with-love free online2018,apps email-with-love, http://dichvuvina.vn
ReplyDelete