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

UNIT 5

Uploaded by

psaranya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

UNIT 5

Uploaded by

psaranya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

UNIT V FILE HANDLING

Console Inputs Output Functions, Disk Inputs Output Functions, Data Files, Command Line
Arguments.

Types of Input/Output functions


A lot of Input/output functions have been defined in the standard libraries. These can be classified as
follows:

 Console I/O functions: These functions allow us to receive input from the input devices like
keyboard and provide output to the output devices like the Visual Display Unit.
 File I/O functions: These functions allow us to access the hard disk or floppy disk to
perform input and output.

Console I/O functions


A console comprises the VDS and the keyboard. The Console Input and Output functions can be
classified into two categories:

 Formatted console I/O functions: These functions allow the user to format the input from
the keyboard and the output displayed in the desired manner.
 Unformatted console I/O functions: These functions do not allow the user this feature.

These various formatted and unformatted console I/O functions are shown in the figure below:

Unformatted Console I/O functions


The unformatted console input/output functions deal with a single character or a string of characters. Let
us see how all these unformatted functions work:

1
Functions Description

This function returns the character that was typed last or was typed most recently. It does not
getch()
display(echo) the character on the screen. It is present in the header file <conio.h>.

This function is the same as getch(). The only difference is that it echoes(displays) the most
getche()
recently used character. It is also present in <conio.h>.

getchar() is a macro that works in a similar manner as getch() and also displays(echoes) the
getchar() character but it needs the user to press the Enter key after the character. It is present in the
header file <stdio.h>.

fgetchar() works in the same manner as getchar() . But fgetchar() is a function.It is also
fgetchar()
present in <stdio.h>.

putch() This function prints a single character on the console.

putchar() This function works in the same way as putch().

fputchar() This function works in the same way as putch().

It takes a string input(single-word or multi-word) from the user. It terminates when the
gets()
Enter key is pressed.

puts() It is used to print the string to the console.

Disk Inputs Output Functions, Data Files


FILES:

Files are used to store large amount of data.

Types of Files:

Files are two types

1.Text files
2.Binary files

1. Text File:
The data are stored as plain text.
2. Binary Files:
The data are stored in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides better
security than text files.

2
Different operations that can be performed on a file are:

1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
2. Opening an existing file (fopen)
3. Reading from file (fscanf or fgets)
4. Writing to a file (fprintf or fputs)
5. Moving to a specific location in afile (fseek, rewind)6.
Closing a file (fclose)

Opening a file - for creation and edit:


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

Syntax:

FILE *filepointer;

filepointer=fopen(“filename”,filemode);

Example:

FILE *fp;
Fp=fopen(“sample.txt”,r);

It opens a file sample.txt in read mode.

File Modes:

S.NO MODE MEANING


1 r Open a text file for reading
2 w Create a text file for writing
3 a Append to a text file
4 rb Open a binary file for reading
5 wb Open a binary file for writing
6 ab Append to a binary file
7 r+ Open a text file for read/write
8 w+ Create a text file for read/write
9 a+ Append or create a text file for read/write
10 r+b Open a binary file for read/write
11 w+b Create a binary file for read/write
12 a+b Append a binary fi le for read/write

Checking the Result of fopen():

When the file cannot be opened due to reasons described below, fopen() will return NULL. The
reasons include the following.

3
1. Use of an invalid filename
2. Attempt to open a file on a disk that is not ready; for example, the drive door isnot closed or
the disk is not formatted.
3. Attempt to open a file in a non-existent directory or on a non-existent diskdrive
4. Attempt to open a non-existent file in mode r

one may check to see whether fopen() succeeds or fails by following code

FILE *fp; FILE *fp;


fp = fopen(“data.dat”,“r”);
if(fp == NULL) if((fp = fopen(“data.dat”, “r”)) ==NULL)
{ {
printf(“Can not open data.dat\n”); printf(“Can not open data.dat\n”);
exit(1); exit(1);
} }

Writing to a File:

In C, when you write to a file, newline characters '\n' must be explicitly added.The stdio
library offers the necessary functions to write to a file:
• fputc(char, file_pointer): It writes a character to the file pointed to by
file_pointer.
• fputs(str, file_pointer): It writes a string to the file pointed to by file_pointer.
• fprintf(file_pointer, str, variable_lists): It prints a string to the file pointed to by
file_pointer. The string can optionally include format specifiers and a list ofvariables variable
lists.

The program below shows how to perform writing to a file:


1. fputc() Function:

#include <stdio.h>
int main() {
int i;
FILE * fptr;
char fn[50];
char str[] = "COMPUTER PROGRAMMING\n";
fptr = fopen("fputc_test.txt", "w"); // "w" defines "writing mode"
for (i = 0; str[i] != '\n'; i++)
{
/* write to file using fputc() function */
fputc(str[i], fptr);
}
fclose(fptr);
return 0;
}
2. fputs () Function:

4
#include <stdio.h>
int main()
{
FILE * fp;
fp = fopen("fputs_test.txt", "w+");
fputs("COMPUTER PROGRAMMING,", fp);
fputs("in C\n", fp);
fputs("Easier than fputc function\n", fp);
fclose(fp);
return (0);
}

3. fprintf()Function:

#include <stdio.h>
int main()
{
FILE *fptr;
fptr = fopen("fprintf_test.txt","w"); // "w" defines "writing mode"
/* write to file */
fprintf(fptr, "Learning C \n");
fclose(fptr);
return 0;
}
4. The fwrite() function:

Syntax:

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.

Example of fwrite() function:


#include<stdio.h>
struct Student
{
int roll;
char name[25];
float marks;
};

void main()
5
{
FILE *fp;
char ch;
struct Student Stu;

fp = fopen("Student.dat","w"); //Statement 1

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

do
{
printf("\nEnter Roll : ");
scanf("%d",&Stu.roll);

printf("Enter Name : ");


scanf("%s",Stu.name);

printf("Enter Marks : ");


scanf("%f",&Stu.marks);

fwrite(&Stu,sizeof(Stu),1,fp);

printf("\nDo you want to add another data (y/n) : ");ch =


getche();

}while(ch=='y' || ch=='Y');

printf("\nData written successfully...");

fclose(fp);
}

Output :

6
Enter Roll : 1
Enter Name : Ashish
Enter Marks : 78.53

Do you want to add another data (y/n) : y

Enter Roll : 2
Enter Name : Kaushal
Enter Marks : 72.65

Do you want to add another data (y/n) : y

Enter Roll : 3
Enter Name : Vishwas
Enter Marks : 82.65

Do you want to add another data (y/n) : n

Data written successfully...

Reading data from a File:

There are three different functions dedicated to reading data from a file
• fgetc(file_pointer): It returns the next character from the file pointed to by the file pointer.
When the end of the file has been reached, the EOF is sent back.
Example:
// C program to illustrate fgetc() function
#include <stdio.h>

int main ()
{
// open the file
FILE *fp = fopen("test.txt","r");

// Return if could not open file


if (fp == NULL)
return 0;

do
{
// Taking input single character at a time
char c = fgetc(fp);

// Checking for end of file


if (feof(fp))
break ;

printf("%c", c);
} while(1);
7
fclose(fp);
return(0);
}

• fgets(buffer, n, file_pointer): It reads n-1 characters from the file and storesthe string in
a buffer in which the NULL character '\0' is appended as the last character.
Example:
// C program to illustrate fgets()
#include <stdio.h>
#define MAX 15

int main()
{
// defining buffer
char buf[MAX];

// using fgets to take input from stdin


fgets(buf, MAX, stdin);
printf("string is: %s\n", buf);

return 0;
}

• fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and


analyze data. It reads characters from the file and assigns the input toa list of variable
pointers variable_adresses using conversion specifiers. Keep in mind that as with scanf,
fscanf stops reading a string when space or newline is encountered.
Example:
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}

The fread() function:

The fread() function is used to read bytes form the file.

Syntax :

fread( ptr, int size, int n, FILE *fp );

8
The fread() function takes four arguments.
ptr : ptr is the reference of an array or a structure where data will be stored afterreading.
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.
Example of fread() function

#include<stdio.h>

struct Student
{
int roll;
char name[25];
float marks;
};

void main()
{
FILE *fp;
char ch;
struct Student Stu;

fp = fopen("Student.dat","r");

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);
}

Output :
Roll Name Marks
1 Ashish 78.53
2 Kaushal 72.65
3 Vishwas 82.65

9
File Sequential Read and Write operation:
#include <stdio.h>
int main()
{
FILE * fp;
char c;
printf("File Handling\n");
fp = fopen("demo.txt", "w");
while ((c = getchar()) != EOF)
{
putc(c, fp);
}

fclose(fp);
printf("Data Entered:\n");

fp = fopen("demo.txt", "r");
while ((c = getc(fp)) != EOF)
{
printf("%c", c);
}
fclose(fp);
return 0;
}

Random Access File Handling:

There is no need to read each record sequentially, if we want to access a particularrecord.C supports
these functions for random access file processing.

1. fseek()
2. ftell()
3. rewind()

1. fseek():

This function is used for seeking the pointer position in the file at the specifiedbyte.

Syntax:
fseek( file pointer, displacement, pointer position);

Where

file pointer -------- It is the pointer which points to the file.


displacement -------- It is positive or negative. This is the number of bytes which are
skipped backward (if negative) or forward( if positive) from the current position. This is attached
with L because this is a long integer.
pointer position ----------- Position defines the point with respect to which the file pointer needs to

10
be moved. It has three values in the form of macros:
 SEEK_SET: Seek from the beginning of the file. It’s value is 0
 SEEK_CUR: Seek from the current position of the file pointer. It’s value is 1
 SEEK_END: Seek from the end of the file. It’s value is 2

Example:
1) fseek( p,10L,0) (or) fseek( p,10L,SEEK_SET)
0 means pointer position is on beginning of the file, from this statement pointer position is
skipped 10 bytes from the beginning of the file.

2)fseek( p,5L,1) (or) fseek( p,5L,SEEK_CUR)


1 means current position of the pointer position. From this statement pointer position is skipped 5
bytes forward from the current position.

3)fseek(p,-5L,2) (or) fseek(p,-5L,SEEK_END)


From this statement pointer position is skipped 5 bytes backward from the current position.

2. ftell()
This function returns the value of the current pointer position in the file. The value is
count from the beginning of the file.

Syntax:
ftell(fptr);

Where fptr is a file pointer.


3. rewind()
This function is used to move the file pointer to the beginning of the given file.

Syntax:
rewind( fptr);

Where fptr is a file pointer.

#include <stdio.h>
#include <stdlib.h>

int main () {
char str1[10], str2[10], str3[10];
int year;
FILE * fp;

fp = fopen ("file.txt", "w+");


fputs("We are in 2024", fp);
11
rewind(fp);
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);

printf("Read String1 |%s|\n", str1 );


printf("Read String2 |%s|\n", str2 );
printf("Read String3 |%s|\n", str3 );
printf("Read Integer |%d|\n", year );

fclose(fp);

return(0);
}

Output :
Read String1 |We|
Read String2 |are|
Read String3 |in|
Read Integer |2024|

Command Line Arguments in C


Command-line arguments are the values given after the name of the program in the command-line shell
of Operating Systems. Command-line arguments are handled by the main() function of a C program.
To pass command-line arguments, we typically define main() with two arguments: the first argument is
the number of command-line arguments and the second is a list of command-line arguments.
Syntax
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
Here,
 argc (ARGument Count) is an integer variable that stores the number of command-line
arguments passed by the user including the name of the program. So if we pass a value to a
program, the value of argc would be 2 (one for argument and one for program name)
 The value of argc should be non-negative.
 argv (ARGument Vector) is an array of character pointers listing all the arguments.
 If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will contain
pointers to strings.
 argv[0] is the name of the program , After that till argv[argc-1] every element is command -
line arguments.
Example

Let's see the example of command line arguments where we are passing one argument with file name.

For better understanding run this code on your Linux machine.


Example
The below example illustrates the printing of command line arguments.
// C program named mainreturn.c to demonstrate the working
12
// of command line argument
#include <stdio.h>

// defining main with arguments


int main(int argc, char* argv[])
{
printf("You have entered %d arguments:\n", argc);

for (int i = 0; i < argc; i++) {


printf("%s\n", argv[i]);
}
return 0;
}

Run this program as follows in Linux:

./program hello and hi everyone

Run this program as follows in Windows from command line:


program.exe hello and hi everyone

Output
You have entered 5 arguments:
./program
hello
and
hi
everyone

But if you pass many arguments within double quote, all arguments will be treated as a single argument
only.

./program "hello c how r u"

Output
You have entered 2 arguments:
./program
hello c how r u
Properties of Command Line Arguments in C
1. They are passed to the main() function.
2. They are parameters/arguments supplied to the program when it is invoked.
3. They are used to control programs from outside instead of hard coding those values inside
the code.
4. argv[argc] is a NULL pointer.
5. argv[0] holds the name of the program.
6. argv[1] points to the first command line argument and argv[argc-1] points to the last
argument.

13

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy