SoC SS-5 Gokul M PSC_UNIT-5
SoC SS-5 Gokul M PSC_UNIT-5
SoC SS-5 Gokul M PSC_UNIT-5
FILES
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.
Purpose:
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
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
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.
Syntax: fclose(file_pointer);
Example:
FILE *p1, *p2;
p1 = fopen(“INPUT.txt”, “r”);
p2 =fopen(“OUTPUT.txt”, “w”);
……..
……..
fclose(p1);
fclose(p2);
#include <stdio.h>
void main()
{
FILE *fp1;
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);
}
⚫ Syntax of fprintf():
fprintf(FILE *fp,"format-string",var-list);
⚫ Syntax of fscanf():
fscanf(FILE *fp,"format-string",var-list);
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 = getche();
}while(ch=='y' || ch=='Y');
printf("\nData written successfully...");
fclose(fp);
}
Output :
Enter Roll : 1
Enter Name : Nilo
Enter Marks : 78.53
Do you want to add another data (y/n) : y
Enter Roll : 2
Enter Name : Nafees
Enter Marks : 89.62
Do you want to add another data (y/n) : n
Data written successfully…
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("file.txt","r"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
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 Nilo 78.53
2 Nafees 89.62
EXAMPLE PROGRAM:
Finding average of numbers stored in sequential access file
#include <stdio.h>
#include <math.h>
// Read the numbers and return average
float average(FILE *input)
{
float term,sum;
int n;
sum = 0.0;
n = 0;
while(!feof(input))
{
fscanf(input,"%f",&term);
sum = sum + term;
n = n + 1;
}
return sum/n;
}
int main ()
{
FILE *input;
float avg;
}
input = fopen("data.txt","r");
avg = average(input);
fclose(input);
printf("The average of the numbers is %f.\n",avg);
return 0;
}
Output:
/* Data in data.txt
10 11 12 13 14 15. */
The average of the numbers is 12.5
FREAD():
fread in C is a standard library function used for reading binary data from a file. It is
part of the stdio.h library.
⚫ ptr: A pointer to the data buffer where the read data will be stored.
⚫ size: The size (in bytes) of each element to be read.
⚫ nmemb: The number of elements to read.
⚫ stream: A pointer to the FILE structure that represents the file from which data will
be read.
⚫ The function returns the number of elements successfully read, which may be less
than nmemb if there's an error or if the end of the file is reached.
⚫ fread is generally used for reading binary data, and if you want to read text data
from a file, you should use functions like fgets or fscanf.
FWRITE()
⚫ fwrite in C is a standard library function used for writing binary data from a file. It
is part of the stdio.h library.
⚫ fwrite is generally used for reading binary data, and if you want to read text data
from a file, you should use functions like fputs or fprintf.
FSEEK()
fseek is a standard library function in C used for repositioning the file pointer within a
file. It allows you to move the file pointer to a specific location, enabling you to read
from or write to a particular position in the file.
stream: A pointer to the FILE structure that represents the file you want to manipulate.
offset: The number of bytes to offset the file pointer from the position specified by the
whence parameter. It can be a positive or negative value.
whence: An integer that specifies the reference position for the offset. It can take one
of the following three values:
SEEK_SET (or 0): The offset is relative to the beginning of the file.
SEEK_CUR (or 1): The offset is relative to the current file position.
SEEK_END (or 2): The offset is relative to the end of the file.
fseek is useful when you need to read or write data at a specific location in a file or
when you want to skip a certain portion of the file.
Ftell():
ftell is a standard library function in C used to get the current file position indicator's
value for a given file stream. It allows you to determine the current offset of the file
pointer within the file.
The C preprocessor is a program that processes C source code before it's compiled. It's
a text substitution tool that transforms the source code according to the preprocessor
directives.
Preprocessor Directives:
Preprocessor directives start with the # symbol and are processed before compilation.
Some common directives include:
⚫ #include: Includes header files or other source files.
⚫ #define: Defines macros.
⚫ #undef: Undefines macros.
⚫ #ifdef: Conditional compilation based on macro definition.
⚫ #ifndef: Conditional compilation based on macro non-definition.
⚫ #if: Conditional compilation based on constant expressions.
⚫ #else: Specifies alternative code for conditional compilation.
⚫ #elif: Combines #else and #if.
⚫ #endif: Ends conditional compilation.
⚫ #pragma: Specifies implementation-defined behavior.
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”
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();
}
addition.txt:
int add(int a,int b)
{
return(a+b);
}
Output:
Enter the numbers:7
4
The Value is 11.
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();
}
Simple Macro:
⚫ It is used to define some constants
Syntax
# define identifier string/integer
Eg:
#define pi 3.14
#define CITY “chennai”
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.
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)
#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.
Nested Macro
Conditional Inclusion:
• It is used to include some conditional statements.
#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
5.7 Command Line Arguments:
Instead of invoking the input statement from inside the program, it is possible to pass
data from the command line to the main() function when the program is executed. These
values are called command line arguments.
Command line arguments are important for your program, especially when you want to
control your program from outside, instead of hard coding those values inside the code.
to write a C program "hello.c" that prints a "hello" message for a user. Instead of
reading the name from inside the program with scanf(), we wish to pass the name from
the command line as follows −
C:\users\user>hello Prakash
The string will be used as an argument to the main() function and then the "Hello
Prakash" message should be displayed.
argc and argv
To facilitate the main() function to accept arguments from the command line, you
should define two arguments in the main() function – argc and argv[].
argc refers to the number of arguments passed and argv[] is a pointer array that points
to each argument passed to the program.
Open any text editor and save the following code as "hello.c" −
#include <stdio.h>
int main (int argc, char * argv[]){
printf("Hello %s", argv[1]);
return 0;
}
The program is expected to fetch the name from argv[1] and use it in the printf()
statement.
Explanation of Syntax
This function initializes the graphics driver and sets the graphics mode. The first
parameter (gd) is a pointer to the graphics driver, which is set to DETECT to detect the
graphics driver automatically. The second parameter (gm) is the graphics mode, which
specifies the resolution and color depth of the screen. The last parameter is a string that
can be used to pass additional arguments to the graphics driver, but in this case, it’s left
empty.
Example:
#include<graphics.h>
#include<conio.h>
void main()
{
intgd=DETECT,gm;
initgraph (&gd,&gm,"c:\\tc\\bgi");
setbkcolor(GREEN);
printf("\t\t\t\n\nLINE");
line(50,40,190,40);
printf("\t\t\n\n\n\nRECTANGLE");
rectangle(125,115,215,165);
printf("\t\t\t\n\n\n\n\n\n\nARC");
arc(120,200,180,0,30);
printf("\t\n\n\n\nCIRCLE");
circle(120,270,30);
printf("\t\n\n\n\nECLIPSE");
ellipse(120,350,0,360,30,20);
getch();
}
Output: