UNIT 5
UNIT 5
Console Inputs Output Functions, Disk Inputs Output Functions, Data Files, Command Line
Arguments.
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.
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:
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>.
It takes a string input(single-word or multi-word) from the user. It terminates when the
gets()
Enter key is pressed.
Types of Files:
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)
Syntax:
FILE *filepointer;
filepointer=fopen(“filename”,filemode);
Example:
FILE *fp;
Fp=fopen(“sample.txt”,r);
File Modes:
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
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.
#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:
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);
fwrite(&Stu,sizeof(Stu),1,fp);
}while(ch=='y' || ch=='Y');
fclose(fp);
}
Output :
6
Enter Roll : 1
Enter Name : Ashish
Enter Marks : 78.53
Enter Roll : 2
Enter Name : Kaushal
Enter Marks : 72.65
Enter Roll : 3
Enter Name : Vishwas
Enter Marks : 82.65
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");
do
{
// Taking input single character at a time
char c = fgetc(fp);
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];
return 0;
}
Syntax :
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;
}
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
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. 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);
Syntax:
rewind( fptr);
#include <stdio.h>
#include <stdlib.h>
int main () {
char str1[10], str2[10], str3[10];
int year;
FILE * fp;
fclose(fp);
return(0);
}
Output :
Read String1 |We|
Read String2 |are|
Read String3 |in|
Read Integer |2024|
Let's see the example of command line arguments where we are passing one argument with file name.
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.
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