You are on page 1of 10

JOGINPALLY B. R.

ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

FILES
What is File?

In C programming, file is a place on disk where a group of related data is stored.

Why files are needed?

When the program is terminated, the entire data is lost in C programming. If you want to keep
large volume of data, it is time consuming to enter the entire data. But, if file is created, these
information can be accessed using few commands.

What are the types of Files?

Files are categorized into two types

1.Text file:It stores texual information like alphabets,numbers,spcial symbols,etc


2.Binary file:It stores the information in the binary form,i.e,tn the same format as it is stored in
the memory.
What is the difference between Text file and Binary file?

In text mode, a newline character is converted into the carriage return-linefeed combination before being
written to the disk. Likewise, the carriage return-linefeed combination on the disk is converted back into a
newline when the file is read by a C program. However, if a file is opened in binary mode, as opposed to
text mode, these conversions will not take place.

The second difference between text and binary modes is in the way the end-of-file is detected. In text
mode, a special character, whose ASCII value is 26, is inserted after the last character in the file to mark
the end of file. If this character is detected at any point in the file, the read function would return the EOF
signal to the program. As against this, there is no such special character present in the binary mode files to
mark the end of file. The binary mode files keep track of the end of file from the number of character
present in the directory entry of the file.

The last difference is storage of numbers. In text file the text and characters are stored one character per
byte, as we expect. But numbers are stored as strings of characters. Thus, 65112, even though it occupies
4 bytes in memory, when transferred to the disk using fprintf(), would occupy 5 bytes, one byte per
character. Here if large amount of data is to be stored in a disk file, using text mode may turn out to be
insufficient. The solution is to open the file in binary mode and use those functions (fread() and fwrite()) )
which store the numbers in binary format. It means each number would occupy same number of bytes on
disks as it occupies in memory.

What are the File Operations?


1.Creating a new file
2.Opening an existing file
1
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
3.Reading from and writing information to a file
4.Closing a file

What are the file I/o functions?

File operation functions in C:

Function Name Operation


Creates a new file for use
fopen()
Opens a new existing file for use
Fclose Closes a file which has been opened for use
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads a integer from a file
putw() Writes an integer to the file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file
rewind() Sets the position to the begining of the file

How to Working with file?

While working with file, you need to declare a pointer of type file. This declaration is needed
for communication between file and program.

FILE *ptr;

How to Defining and Opening a file?

If we want to store data in a file into the secondary memory, we must specify certain things about the
file to the operating system. They include the fielname, data structure, purpose.

The general format :

FILE *fp;
fp=fopen(“filename”,”mode”);

 The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier,
File is a structure that is defined in the I/O Library.
 The second statement opens the file named filename and assigns an identifier to the FILE type
pointer fp. This pointer, which contains all the information about the file, is subsequently used as
a communication link between the system and the program.
 The second statement also specifies the purpose of opening the file.

2
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

The mode does this job:

r open the file for read only.


w open the file for writing only.
a open the file for appending data to it.

Example:

FILE *p1, *p2;


p1=fopen(“data”,”r”);
p2=fopen(“results”,”w”);

In these statements the p1 and p2 are created and assigned to open the files data and results
respectively the file data is opened for reading and result is opened for writing. In case the results file
already exists, its contents are deleted and the files are opened as a new file. If data file does not exist
error will occur.

What are the opening modes?

Opening Modes in Standard I/O

File Mode Meaning of Mode During Inexistence of file

If the file does not exist, fopen()


R Open for reading. returns NULL.

If the file exists, its contents are


overwritten. If the file does not exist,
W Open for writing. it will be created.

Open for append. i.e,


Data is added to end of If the file does not exists, it will be
A file. created.

Open for both reading If the file does not exist, fopen()
r+ and writing. returns NULL.

w+
Open for both reading If the file exists, its contents are
3
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

Opening Modes in Standard I/O

File Mode Meaning of Mode During Inexistence of file

and writing. overwritten. If the file does not exist,


it will be created.

Open for both reading If the file does not exists, it will be
a+ and appending. created.

How to Closing a File?

The input output library supports the function to close a file.

The general format:

fclose(file_pointer);

A file must be closed as soon as all operations on it have been completed. This would close the file
associated with the file pointer.

Example:

FILE *p1 *p2;


p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
….

fclose(p1);
fclose(p2)

The above program opens two files and closes them after all operations on them are completed, once a
file is closed its file pointer can be reversed on other file.

Describe about fprintf() and fscanf() functions?

The fprintf and fscanf functions are identical to printf and scanf functions except that they work on files.
The first argument of theses functions is a file pointer which specifies the file to be used.

The general form of fprintf is

4
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 fprintf(fp,”control string”, list);
 Where fp id a file pointer associated with a file that has been opened for writing. The control
string is file output specifications list may include variable, constant and string.
 fprintf(f1,%s%d%f”,name,age,7.5);
 Here name is an array variable of type char and age is an int variable

The general format of fscanf is

 fscanf(fp,”controlstring”,list);
 This statement would cause the reading of items in the control string.

How toWriting to a file?

#include <stdio.h>
int main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}

This program takes the number from user and stores in file. After you compile and run this
program, you can see a text file program.txt created in C drive of your computer. When you
open that file, you can see the integer you entered.

Similarly, fscanf() can be used to read data from file.

How toReading from file?

#include <stdio.h>
int main()
{
int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
5
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
fclose(fptr);
return 0;
}

If you have run program above to write in file successfully, you can get the integer back entered
in that program using this program.

Explain about getc() and putc() functions?

getc()

The getc() function returns the next character from the specified input stream and increment file position
indicator. The character is read as an unsigned char that is converted to an integer.

Declaration:

 int getc(FILE *stream);

Example:

1. #include <stdio.h>
2. #include <stdlib.h>
3. int main()
4. {
5. FILE *fptr;
6. char c;
7. clrscr();
8. if((fptr = fopen(“TEST”,”r”))==NULL)
9. {
10. printf(“Cannot open file\n”);
11. exit(1);
12. }
13. while((c=getc(fptr))!=EOF)
14. putchar(c);
15. if(fclose(fptr))
16. pritf(“File close error\n”);
17. getch();
18. return 0;
19. }

putc()

The putc() function writes the character ch to the specified stream at the current file position and then
advance the file position indicator. Even though the ch is declared to be an int, it is converted by putc()
into an unsigned char.

Declaration:

 int putc(int ch, FILE *stream);


6
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Example:

1. #include <stdio.h>
2. #include <stdlib.h>
3. void main()
4. {
5. FILE *fptr;
6. char text[100];
7. int i=0;
8. clrscr();
9. printf(“Enter a text:\n”);
10. gets(text);
11. if((fptr = fopen(“TEST”,”w”))==NULL)
12. {
13. printf(“Cannot open file\n”);
14. exit(1);
15. }
16. while(text[i]!=’\0’)
17. putc(text[i++],fptr);
18. if(fclose(fptr))
19. pritf(“File close error\n”);
20. getch();
21. }

Explain about getw() and putw() Functions?

These are integer-oriented functions. They are similar to get c and putc functions and are used to read
and write integer values. These functions would be usefull when we deal with only integer data. The
general forms of getw and putw are:

putw(integer,fp);
getw(fp);

Example:

1. /*Example program for using getw and putw functions*/


2. #include< stdio.h >
3. main()
4. {
5. FILE *f1,*f2,*f3;
6. int number I;
7. printf(“Contents of the data filenn”);
8. f1=fopen(“DATA”,”W”);
9. for(I=1;I< 30;I++)
10. {
11. scanf(“%d”,&number);
12. if(number==-1)
13. break;
14. putw(number,f1);
7
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
15. }
16. fclose(f1);
17. f1=fopen(“DATA”,”r”);
18. f2=fopen(“ODD”,”w”);
19. f3=fopen(“EVEN”,”w”);
20. while((number=getw(f1))!=EOF)/* Read from data file*/
21. {
22. if(number%2==0)
23. putw(number,f3);/*Write to even file*/
24. else
25. putw(number,f2);/*write to odd file*/
26. }
27. fclose(f1);
28. fclose(f2);
29. fclose(f3);
30. f2=fopen(“ODD”,”r”);
31. f3=fopen(“EVEN”,”r”);
32. printf(“nnContents of the odd filenn”);
33. while(number=getw(f2))!=EOF)
34. printf(“%d%d”,number);
35. printf(“nnContents of the even file”);
36. while(number=getw(f3))!=EOF)
37. printf(“%d”,number);
38. fclose(f2);
39. fclose(f3);
40. }

Describe about Appending?

 When a file is opened for appending, it will be created if it does not already exist and it will be
initially empty. If it does exist, the data input point will be positioned at the end of the present
data so that any new data will be added to any data that already exists in the file. Using the a
indicates that the file is assumed to be a text file. Here is a program that will add text to a file
which already exists and there is some text in the file.

Example:

1. #include <stdio h>


2. int main()
3. {
4. FILE *fp
5. file = fopen("file.txt","a");
6. fprintf(fp,"%s","This is just an example :)"); /*append some text*/
7. fclose(fp);
8. return 0;

Discribe about Error Handling During I/O Operation?

It is possible that an error may occur during I/O operations on a file. Typical error situations include:
8
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
1. Trying to read beyond the end of file mark
2. Device overflow
3. Trying to use a file that has not been opened.
4. Trying to perform an operation on a file,when the file is opened for another type of operation.
5. Opening a file with an invalid filename.
6. Attempting to write to a write-protected file.

Discribe about Random Access Files?

Random Access files are different from sequential files in two important ways:

 You can jump instantly to any structure in the file, which provides random access as in an array.
 You can change the contents of a structure anywhere in the file at any time.

Once one opens a file one can read, write, or seek any arbitrary structure in the file. C maintains a "file
pointer" to enable these functions. When the file is opened, the pointer points to record 0 (the first record
in the file). Any read operation reads the currently pointed-to structure and moves the pointer to the next
record or structure. A write is done at the currently pointed-to structure and moves the pointer down one
structure. Seek moves the pointer to the specified record.

fseek() Sets the position to a desired point in the file


ftell() Gives the current position in the file
rewind() Sets the position to the begining of the file

The code below demonstrates random access file techniques.

1. #include <stdio h>


2. struct arec{
3. int x,y,z;
4. };
5. /* writes and then reads 5 records
6. from the file "junk". */
7. int main(void)
8. {
9. int i,j;
10. FILE *f;
11. struct arec myrec;
12. /* create the file of 5 records */
13. f=fopen("junk","w");
14. if (!f)
15. return 1;
16. for (i=1;i&lt;=5; i++)
17. {
18. myrec.x=i;
19. fwrite(&amp;r,sizeof(struct arec),1,f);
20. }
21. fclose(f);
22. /* read the 5 records */
9
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
23. f=fopen("junk","r");
24. if (!f)
25. return 1;
26. for (i=1;i&lt;=5; i++)
27. {
28. fread(&amp;myrec,sizeof(struct arec),1,f);
29. printf("%d\n",.rx);
30. }
31. fclose(f);
32. printf("\n");
33. /* use fseek to read the 5 records in reverse order */
34. f=fopen("junk","r");
35. if (!f)
36. return 1;
37. for (i=4; i&gt;=0; i--)
38. {
39. fseek(f,sizeof(struct arec)*i,SEEK_SET);
40. fread(&amp;myrec,sizeof(struct arec),1,f);
41. printf("%d\n",myrec.x);
42. }
43. fclose(f);
44. printf("\n");
45. /* use fseek to read 3rd record,
46. change it, and write it back */
47. f=fopen("junk","r+");
48. if (!f)
49. return 1;
50. fseek(f,sizeof(struct arec)*2,SEEK_SET);
51. fread(&amp;r,sizeof(struct arec),1,f);
52. myrec.x=100;
53. fseek(f,sizeof(struct arec)*3,SEEK_SET);
54. fwrite(&amp;myrec,sizeof(struct arec),1,f);
55. fclose(f);
56. printf("\n");
57. return 0;
58. }

10

You might also like