The document discusses file management in C programming. It defines a file as a sequence of bytes stored on disk for permanent storage of data. It describes basic file operations like opening, reading, writing and closing files. It explains functions for high level input/output like fopen(), fclose(), getc(), putc(), fprintf(), fscanf(), getw(), putw() and their usage. It also covers error handling functions like feof() and ferror(). The document discusses random access of files using functions like ftell(), fseek() and rewind(). It finally talks about command line arguments and how they are passed to main() in C programs.
2. File management
Introduction
Defining and Opening a File
Closing a File
Input/output operations on File
Error Handling During I/O Operation
Random Access to Files
Command Line Arguments
3. Introduction
A file represents a sequence of bytes on the disk where a
group of related data is stored.
File is created for permanent storage of data. It is a ready
made structure.
Real life problems involve large volume of data and in such
cases, the console oriented I/O operations pose two major
problems
It becomes cumbersome and time consuming to handle large
volumes of data through terminals.
The entire data is lost when either the program is terminated or
computer is turned off .
4. Basic File operations .They are,
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
There are two distinct ways to perform file operations in c.
The first one is known as the low-level I/O and used UNIX
system calls.
The second method is know n as the high-level I/O operation
and uses function in C’s standard I/O library
It is used for store a data permanently in computer. Using this
concept we can store our data in Secondary memory (Hard disk).
5. High level I/O function
S.No
Function Name Operation
1
fopen() Creates a new file for use
Opens a new existing file for use
2
fclose() Closes a file which has been opened for use
3
getc() Reads a character from a file
4
putc() Writes a character to a file
5
fprintf() Writes a set of data values to a file
6
fscanf() Reads a set of data values from a file
7 getw() Reads a integer from a file
8 putw() Writes an integer to the file
9 fseek() Sets the position to a desired point in the file
10 ftell() Gives the current position in the file
11 rewind() Sets the position to the beginning of the file
6. Defining AND OPENING file
• To store data in a file in the secondary memory specify
certain things about the file to the operating system. They
include ,
• Filename is a string of characters that makeup a valid for the
operating system.
• Data structure of a file is defined as ‘File’ in the library of
standard I/O function definition .
• File is a defined data type.
• It contains two parts, a Primary name and optional period
with extension.
1.File name
2.Data structure
3. Purpose
Example:
Input .data
PROG.C
7. File operations
Fopen function: The general format for declaring and opening
a file is
The variable fp has a pointer to the data type File opens
the File name and pointer assigns an identifier to the File type
pointer fp.
This pointer which contains all the information about the File
subsequently used as a communication link between the system
and the program.
Mode can be one the following
r - open the file for reading only.
w - open the file writing only.
a - open the file for appending (adding) data to each.
FILE *fp;
Fp = fopen ( “file name”, “mode” );
8. File opening with example
Both ‘file name’ and ‘mode’ are specified as string they should
be enclosed in double quotation marks (“ ”).
Example:
Where fp1,fp2 are pointer
The ‘fp1’ is opens the File named as data for reading mode
only.
Then ‘fp2’ is opens the File named as result for writing
mode only.
FILE * fp1, *fp2;
Fp1 = fopen (“data’’, “r”);
Fp2= fopen (“result”, “w”);
9. Program for file opening
Reading
#include<stdio.h>
void main()
{
FILE *fopen(), *fp;
int c;
fp = fopen("prog.c","r");
c = getc(fp) ;
while (c!= EOF)
{
putchar(c);
c = getc(fp);
}
fclose(fp);
}
Writing
#include <stdio.h>
int main()
{
FILE *fp;
file = fopen("file.txt","w");
/*Create a file and add text*/
fprintf(fp,"%s",” example :");
/*writes data to the file*/
fclose(fp); /*done!*/
return 0;
}
Appending
#include <stdio.h>
int main()
{
FILE *fp ;
file = fopen("file.txt","a");
fprintf(fp,"%s"," example :");
/*append some text*/
fclose(fp);
return 0;
}
10. Additional modes of operation
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode
11. Closing a file
A File must be closed after all operations have been
completed. The general form of fclose function is
Syntax:
Example: :
This program opens two files and closes them after all
operations on them are completed once a file is closed its file
pointer can be reused for another file.
Fclose (file pointer);
Fp1 =fopen (“input”, "W”);
Fp2 = fopen(“output”, “r”);
……….
……….
Fclose(fp1);
Fclose(fp2);
……….
12. Program for closing a file
#include <stdio.h>
main( )
{
FILE *fp;
char c;
funny = fopen("TENLINES.TXT", "r");
if (fp == NULL)
printf("File doesn't existn");
else
{
do
{
c = getc(fp); /* get one character from the file */
putchar(c); /* display it on the monitor */
}
while (c != EOF); /* repeat until EOF (end of file) */
}
fclose(fp);
}
13. getc function
The getc is used to read a character from a file that has
been opened in read mode.
Syntax:
The read a character from the file whose pointer is file
pointer and assigned the reading character to ‘C’.
The reading is terminated when getc encounter end of file
mark EOF.
Example :
File *fp;
Char c;
………….
Fp=fopen (“input”, “r”);
While(c=getc(fp)!=Eof)
Putchar ( c );
C=getc (file pointer);
Input/output operations on files
14. putcfunction
The putc is used to write a character to a file that has been
opened in write mode.
Syntax:
The read a character through to the variable and put these
character through whose file pointer is fp.
The writing is terminated when putc encounters the end of file
mark EOF.
Example:
Putc (c,fp);
FILE *fp;
Char C;
………..
Fp=fopen(“input”, “w”);
While (c = getchar( c )!= EOF)
Putc(c, fp);
15. getw function
The simplest integer oriented file I/o function is getw that has
been opened in read mode .
Syntax:
Where read an integer value from the file whose file pointer is
fp and assigned the reading numbers to num.
The reading is terminated when getw encounters the end of file
mark EOF.
Example :
Num =getw (fp);
FILE *fp
Int num;
……….
Fp=fopen (“input”, "r”);
While (num=getw(fp)!=EOF)
Printf(“%d”, num);
16. Putw function
The simplest I/O integer oriented function is putw is used to
create an integer value to a file that has been opened in write
mode.
Syntax:
The read a number through to the variable ‘num’ and put the
number into the file whose file pointer is fp.
The waiting is terminted when ‘Putw’ encounters the end of
file mark Eof (i.e,num=0)
Example :
FILE *fp
Int num;
Fp=fopen (“INPUT”, "w”);
Scanf(“%d”, & num);
While (num!= fp)
Putw(num,fp);
Scanf(“%d”, & num);
Putw(num,fp);
17. fprintf function
The fprintf statement is used to write data items to the file whose
file pointer is opened in the writing mode.
‘fprintf’ perform I/O operations an files.
Syntax:
Where ‘fp’ is a file pointer associated with a file that has been
opened for writing.
The control string contains output specifications for the items in the
list.
The list may be including variable constants and strings.
Example :
Where ‘name is an array variable of type and age is an int
variable.
fprintf (fp1, "%s %d %f”, name age,7.5);
Fprintf (fp, "control string", list);
18. fscanffunction
The fscanf function is used to read data items to the file whose
pointer is opened in the reading mode.
fscanf function performs I/O operations on files.
Syntax:
This statement reading of the items in the list from the file
specified by fp. The control string contains input specifications
for the items in the list.
Example :
Where “item” is an array variable of type and quantity is an int
variable.
fscanf returns the no. of items when the end of file is reached 'i'
returns the value EOF.
fscanf (fp1, “%s %d”, item & quantity);
fscanf (fp, “control string”, list);
19. #include <stdio.h>
int main ()
{
char name [20];
int age, length;
FILE *fp;
fp = fopen ("test.txt","w");
fprintf (fp, "%s %d", “Fresh2refresh”, 5);
length = ftell(fp); // Cursor position is now at the end of file
/* You can use fseek(fp, 0, SEEK_END); also to move the cursor to the end of the file */
rewind (fp); // It will move cursor position to the beginning of the file
fscanf (fp, "%d", &age);
fscanf (fp, "%s", name);
fclose (fp);
printf ("Name: %s n Age: %d n",name,age);
printf ("Total number of characters in file is %d", length);
return 0;
}
OUTPUT:
Name: Fresh2refresh
Age: 5
Total number of characters in file is 15
Program for printf and scanf
20. Error handling during i/o operations
It is possible that an error may occur during I/O operations on a
file. Typical error situations include:
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.
21. feof function
The feof function can be used to test for an end of file
condition .
It takes a file pointer as an argument and returns a non-zero
integer value id all of the data from the specified file has been
read and returns zero otherwise.
Example:
This statement gives the end of data when encountered end of
file condition.
If (feof (fp)
Printf(“end of file”);
22. ferror function
The ferror function is also takes a file pointer its argument
and returns a non-zero integer.
If an error has been detected up to that point during processing
it returns zero otherwise.
Example :
Print the error message if the reading is not successful.
If (ferror (fp)!=0)
Printf(“file could not be open”);
23. Program for ferror function
#include <stdio.h>
int main()
{
FILE *fp;
char c;
fp = fopen("file.txt", "w");
c = fgetc(fp);
if( ferror(fp) )
{
printf("Error in reading from file : file.txtn");
}
clearerr(fp);
if( ferror(fp) )
{
printf("Error in reading from file : file.txtn");
}
fclose(fp);
return(0);
}
Output:
Error in reading from file : file.txt
24. Random access to files
This file functions are useful to reading and writing data
sequentially.
When we are interested in accessing only a particular part of a
file and not in reading the other parts.
This can be achieved with the help of the functions fseek, ftell
and rewind available in the I/O library.
25. ftell function
The ftell function is useful in saving the current position of a
file, which can be used later in the program .
It takes the following form
Syntax:
Where ‘n’ gives the relative offset (in bytes) of the current
position. This means that ‘n’ bytes have already read.
Example : rewind(fp);
n = ftell ( fp);
n = ftell ( fp);
26. Rewind function
The Rewind function takes a file pointer and resets the
position to the start of the (in bytes) file. The statement is
It will assign ‘o’ to n’ because the file position has been set to
the start of the file by rewind.
The first byte in the file is numbered as ‘0’ second as ‘1’ and
so on.
This function help us in reading a file more than once, without
having to close and open file.
Rewind (fp);
N = ftell(fp);
27. Fseek function
Fseek function is used to move the file position to a desired
location within the file. It takes the following form
Syntax:
Here ‘file pointer’ is a pointer to the file, ‘offset’ is a number or
variable of type ‘long’, and position is an integer variable. The
offset specifies the positions (bytes) to be moved from the
location specified by position.
Fseek (file pointer, offset, position);
Value Meaning
0 Beginning of the file
1 Current position
2 End of the file
28. The Offset may be ‘+’ve meaning moved forwards, or ‘-
‘ ve meaning moved backwards.
Example:
Example:
Fseek(fp,oL,0) goto beginning
Fseek(fp,m,0) move (n+1)th byte in the file
Fseek (fp,m,1) goto forward by ‘m’ bytes
Fseek (fp,-m,1) goto backward by ‘m’ bytes from the current position
Fseek (fp ,-m,2) goto backward by ‘m’ bytes from the end
29. program
#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("%ct",ch);
}
}
fclose(fp);
getch();
}
30. Command line arguments
It is parameter supplied to a program when the program is
invoked.
This parameter may represent a file name the program
should process.
It is possible to pass some values from the command line to
your C programs when they are executed. These values are
called command line arguments.
Many times they are important for your program especially
when you want to control your program from outside instead of
hard coding those values inside the code.
31. The command line arguments are handled using main()
function arguments where argc refers to the number of
arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.
Syntax:
main(int argc, char *argv[])
{
………….
………….
}
32. Program for command line arguments
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %sn", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.n");
}
else
{
printf("One argument expected.n");
}
}
$./a.out testing
The argument supplied is testing.
$./a.out testing1 testing2
Too many arguments supplied.
Single argument
Twoargument