0% found this document useful (0 votes)
38 views

Files in C

Uploaded by

Srivatsan SP
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Files in C

Uploaded by

Srivatsan SP
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Unit - V

Files and Preprocessor

1
FILES
• Files are places where data can be stored permanently.
• In C, each file is simply a sequential stream of bytes. C imposes
no structure on a file.
• A file must first be opened properly before it can be accessed for
reading or writing. When a file is opened, a stream is associated
with the file.

2
Defining and opening file:
• In order to define and open file we need
• Filename (e.g. sort.c, input.txt)
• Data structure (e.g. FILE)
• Purpose (e.g. Reading, Writing, Appending)
Filename: String of characters that make up a valid file name.
• May contain two parts
• Primary
• Optional period with extension
• Examples: a.out, prog.c, temp, text.out

3
Data Structure:
FILE *fptr1, *fptr2 ;
The above statement declares that
• fptr1 and fptr2 are pointer variables of type FILE.
• They will be assigned the address of a file descriptor, that is, an area of
memory that will be associated with an input or output stream.

General format for opening file:


• FILE *fp; /*variable fp is pointer to type FILE*/
• fp = fopen(“filename”, “mode”); /*opens file with name filename , assigns
identifier to fp */
• fp
• contains all information about file
• Communication link between system and program
4
• Various modes of operation on files
• r open file for reading only
• w open file for writing only
• a open file for appending (adding) data
• Various modes of operations on files:
• Writing mode
• If the file already exists then contents are deleted,
• Else a new file with specified name is created
• Appending mode
• If the file already exists then the file is opened with contents and further updated.
• Else new file created
• Reading mode
• If the file already exists then it is opened with contents.
• Else error occurs.
5
Example:
FILE *p1, *p2, *p3;
p1 = fopen(“data”,”r”);
p2= fopen(“results”, w”);
p3= fopen(“results”, a”);
Closing a File:
• File must be closed as soon as all operations on it completed.
• Ensures
• All outstanding information associated with file flushed out
from buffers
• All links to file broken
• If we want to change mode of file, then first close and then open again.
6
• Example:
FILE *p1, *p2;
p1 = fopen(“INPUT.txt”, “r”);
p2 =fopen(“OUTPUT.txt”, “w”);
……..
……..
fclose(p1);
fclose(p2);

7
Input and Output Operations with Files:
• C provides several different functions for reading/writing in to files.
• Some of them are
• getc() – read a character
• putc() – write a character
• fprintf() – write set of data values
• fscanf() – read set of data values

8
getc() and putc():
• This function handles one character at a time.
• Syntax: putc(c,fp1);
• c : a character variable
• fp1 : pointer to file opened with mode w
• Syntax: c = getc(fp2);
• c : a character variable
• fp2 : pointer to file opened with mode r
• File pointer moves by one character position after every getc() and putc()
• getc() returns end-of-file marker EOF when file end reached

9
//Program for file manipulation using getc()
and putc();
#include <stdio.h>
void main()
{
FILE *f1;
char c;
f1= fopen(“INPUT”, “w”); /* open file for writing */
while((c=getchar()) != EOF) /*get char from keyboard until CTL-Z*/
putc(c,f1); /*write a character to INPUT */
fclose(f1); /* close INPUT */
f1=fopen(“INPUT”, “r”); /* reopen file */
while((c=getc(f1))!=EOF) /*read character from file INPUT*/
printf(“%c”, c);/* print character to screen */
fclose(f1);
}

10
fprintf() and fscanf():

• Syntax of fprintf():
fprintf(FILE *fp,"format-string",var-list);
• Syntax of fscanf():
fscanf(FILE *fp,"format-string",var-list);

11
#include<stdio.h>
//Program for file manipulation using
void main() fprintf()
{
FILE *fp;
int roll;
char name[25];
float marks;
char ch;
fp = fopen(“student.txt","w"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
12
do
{
printf("\nEnter Roll : ");
scanf("%d",&roll);
printf("\nEnter Name : ");
scanf("%s",name);
printf("\nEnter Marks : ");
scanf("%f",&marks); fprintf(fp,"%d%s%f",roll,name,marks);
printf("\nDo you want to add another data (y/n) : ");
ch = getc();
}while(ch=='y' || ch=='Y');
printf("\nData written successfully...");
fclose(fp);
} 13
Output :
Enter Roll : 1
Enter Name : ECE
Enter Marks : 78.53
Do you want to add another data (y/n) : y
Enter Roll : 2
Enter Name : SVCE
Enter Marks : 89.62
Do you want to add another data (y/n) : n
Data written successfully...

14
#include<stdio.h>
void main() //Program for file manipulation using
{ fscanf()
FILE *fp;
char ch;
fp = fopen(“student.txt","r"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}

15
printf("\nData in file...\n");
while((fscanf(fp,"%d%s%f",&roll,name,&marks))!
=EOF) //Statement 2
{
printf("\n%d\t%s\t%f",roll,name,marks);
}
fclose(fp);
}
Output :
Data in file...
1 ECE 78.53
2 SVCE 89.62
16
fread()
• The C library function fread() reads data from the given file stream.
Syntax:
fread( ptr, int size, int n, FILE *fp );
Parameters
• The fread() function takes four arguments.
ptr : ptr is the reference of an array or a structure where data will be
stored after reading.
size : size is the total number of bytes to be read from file.
n : n is number of times a record will be read.
FILE* : FILE* is a file where the records will be read.
17
Example void main()
struct Student {
{ FILE *fp;
int roll; char ch;
char name[25]; struct Student Stu;
float marks;
}; fp = fopen("Student.dat","r"); //Statement 1

if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}

printf("\n\tRoll\tName\tMarks\n");

while(fread(&Stu,sizeof(Stu),1,fp)>0)
printf("\n\t%d\t%s\t%f",Stu.roll,Stu.name,Stu.marks);

fclose(fp);
}
18
fwrite() function
• The fwrite() function is used to write records (sequence of bytes) to the file.
Syntax of fwrite() function
fwrite( ptr, int size, int n, FILE *fp );

The fwrite() function takes four arguments.


ptr : ptr is the reference of an array or a structure stored in memory.
size : size is the total number of bytes to be written.
n : n is number of times a record will be written.
FILE* : FILE* is a file where the records will be written in binary mode.

19
do
struct Student
{
{
printf("\nEnter Roll : ");
int roll;
scanf("%d",&Stu.roll);
char name[25];
float marks;
printf("Enter Name : ");
};
scanf("%s",Stu.name);

void main() printf("Enter Marks : ");


{ scanf("%f",&Stu.marks);
FILE *fp;
char ch; fwrite(&Stu,sizeof(Stu),1,fp);
struct Student Stu;
printf("\nDo you want to add another data (y/n) : ");
fp = fopen("Student.dat","w"); ch = getche();

if(fp == NULL) }while(ch=='y' || ch=='Y');


{
printf("\nCan't open file or file doesn't exist."); printf("\nData written successfully...");
exit(0);
} fclose(fp);
}
20
fseek()
• The C library function int fseek(FILE *stream, long int offset, int whence) sets the
file position of the stream to the given offset.
Syntax:
int fseek(FILE *stream, long int offset, int whence);
• stream − This is the pointer to a FILE object that identifies the stream.
• offset − This is the number of bytes to offset from whence.
• whence − This is the position from where offset is added. It is specified by one of
the following constants −
SEEK_SET Beginning of file
SEEK_CUR Current position of the file pointer
SEEK_END End of file

21
#include <stdio.h>

int main () {
FILE *fp;

fp = fopen("file.txt","w+");
fputs(“Hello world", fp);

//fseek( fp, 7, SEEK_SET );


fputs(" C Programming Language", fp);
fclose(fp);

return(0);
}

file.txt

Hello wC Programming Language

22
rewind()
• The C library function void rewind(FILE *stream) sets the file position
to the beginning of the file of the given stream.
Syntax:
void rewind(FILE *stream)

23
int main () printf("%c", ch);
{ }
char str[] = "This is tutorialspoint.com"; rewind(fp); Let us assume we have a text file file.txt
FILE *fp; printf("\n"); that have the following content −
int ch; while(1) {
ch = fgetc(fp); This is Problem Solving using C
/* First let's write some content in the file */ if( feof(fp) ) {
fp = fopen( "file.txt" , "w" ); break ;
fwrite(str , 1 , sizeof(str) , fp ); } Now let us compile and run the
fclose(fp); printf("%c", ch); above program to produce the
following result −
fp = fopen( "file.txt" , "r" ); }
while(1) { fclose(fp); This is Problem Solving using C
ch = fgetc(fp); This is Problem Solving using C
if( feof(fp) ) { return(0);
break ; }
}

24
ftell()
• The C library function long int ftell(FILE *stream) returns the current
file position of the given stream.
Syntax:
long int ftell(FILE *fp);
This function returns the current value of the position indicator. If an
error occurs, -1L is returned, and the global variable errno is set to a
positive value.

25
int main () {
FILE *fp;
int len;

fp = fopen("file.txt", "r"); Let us assume we have a text file file.txt, which has the
if( fp == NULL ) { following content − Hello world
perror ("Error opening file");
return(-1); Total size of file.txt = 26 bytes
}
fseek(fp, 0, SEEK_END);

len = ftell(fp);
fclose(fp);

printf("Total size of file.txt = %d bytes\n", len);

return(0);
}

26
Preprocessor
• It is a program that processes the source program before compilation.
• Preprocessor is a separate step in the compilation process.
• In simple terms, a C preprocessor is a just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual compilation.
• All preprocessor commands begin with hash symbol(#). A preprocessor directive
should begin in the first column.
• It operates under the following directives:

• File Inclusion
• Macro substitution
• Conditional inclusion

27
File Inclusion
• It is used to include some file that contains functions or some
definitions.
• Syntax:
#include<filename> (or)
#include“filename”
• Eg: #include<stdio.h>
#include “ex.c”
These directives tell the C to get stdio.h from system libraries and add
the text to the current source file.
28
Example
#include<stdio.h>
#include<conio.h>
#include "addition.txt"
void main()
{
int a,b;
printf("\nEnter the numbers:");
scanf("%d%d",&a,&b);
printf("The Value is %d",add(a,b));
getch();
}
29
addition.txt
int add(int a,int b)
{
return(a+b);
}

30
Output

Enter the numbers:7


4
The Value is 11

31
Example
#include<stdio.h>
#include<conio.h>
#include "fact.c"
void main()
{
int a;
printf("\nEnter the number:");
scanf("%d",&a);
printf("The factorial of %d! is %d",a,rec(a));
getch();
}
32
Macro Substitution
• It is used to define and use integer, string, or identifier in the source
program
• The three forms of macros are
• Simple Macro
• Argumented Macro
• Nested Macro

33
Simple Macro

• It is used to define some constants


• Syntax
#define identifier string/integer
• Eg:
#define pi 3.14
#define CITY “chennai”

34
Example
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define CITY "chennai"
void main()
{
printf("The Value is %f",2*pi);
printf("\nThe Value CITY is %s",CITY);
getch();
}

Output:
The Value is 6.280000
The Value CITY is chennai 35
Argumented Macro
• It is used to define some complex forms in the source
program.
• Syntax:
#define identifier (v1,v2,….) string/integer

• Eg:
#define cube(n) (n*n*n)

36
Example
#include<stdio.h>
#include<conio.h>
#define cube(n) (n*n*n)
void main()
{
printf("The Value of 3 cube is %d",cube(3));
getch();
}

Output:
The Value of 3 cube is 27
37
Nested Macro

• Here one macro is used by another macro.

• Eg:
#define a 3
#define sq a*a

38
Example
#include<stdio.h>
#include<conio.h>
#define a 3
#define sq a*a
void main()
{
printf("The Value is %d",sq);
getch();
}

Output:
The Value is 9
39
Conditional Inclusion

• It is used to include some conditional statements.

• Example: #if, #else, #elif, #endif

40
Example
#include<stdio.h>
#include<conio.h>
#define a 3
#ifdef a
#define c a+5
#endif
void main()
{
printf("\nThe value C is %d",c);
getch();
}

Output:
The value C is 8

41
Storage classes
• Every C variable has a storage class,
• Storage classes determines :
• The part of memory where storage is allocated for variable
• What will be the initial value of the variable if not assigned
• How long the storage allocation continues to exists.
• The scope which specifies the part of the program over which a
variable name is visible
• Categories of storage classes in C:
• Automatic
• External
• Static
• Register

42
Automatic (auto)
• By default, variables in C uses the auto storage class.
• The variables are automatically created when needed and deleted
when they fall out of the scope.
• Ex:
void main()
{ Output
auto int a=10;
{ 30
auto int a=20; 20
{ 10
auto int a =30;
printf(“%d”,a);
}
printf(“\n%d”,a);
}
printf(“\n%d”,a);
} 43
Automatic (auto)

• Storage : Memory
• Scope : Within the block in which variable is
defined
• Life : Till the program control is within the
block
• Default value : Un predictable (Garbage Value)

44
External (Global) -extern
• Global variables are accessible from within any block & or remains in
existence for the entire execution of the program.
• Using global variables we can transfer information into a function without using
arguments
• Ex:
void sum();
int a=10,b=5;
void main() Output
{
clrscr(); Added values : 15
sum();
getch();
}
void sum()
{
int c;
c=a+b;
printf(“Added values : %d”,c); 45
External - extern

• Storage : Memory
• Scope : Global
• Life : During entire program execution
• Default value : zer0

46
Static variables - static
• Storage: Memory
• Scope : Local to the block in which the variable is defined
• Life : Value of the variables persist between different function calls
• Default value : zer0
• Ex:
void incr();
void main() Output
{
incr(); 123
incr();
incr();
}
void incr()
{
static int a=1;
printf(“%d\t”,a);
a=a+1;
47
}
Register variables - register
• Register variables are usually stored in memory and passed
back & forth to the processor as needed.

• Storage: CPU Registers


• Scope : Local to the block in which the variable is
defined
• Life : Till the program control is within the block in
which variable is defined.
• Default value : Unpredictable(Garbage).
• Ex:

void main()
{
register int counter; 48

You might also like