Professional Documents
Culture Documents
ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
FILES
What is File?
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.
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.
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;
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.
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
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Example:
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.
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
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Open for both reading If the file does not exists, it will be
a+ and appending. created.
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:
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.
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.
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
fscanf(fp,”controlstring”,list);
This statement would cause the reading of items in the control string.
#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.
#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.
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:
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:
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. }
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:
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:
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.
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.
10