ME171: Computer Programming Language
File Directed Input Output
Console based Input/Output
▪ Console oriented – use terminal (keyboard/screen)
▪ scanf(“%d”,&i) – read data from keyboard
▪ printf(“%d”,i) – print data to monitor
▪ Suitable for small volumes of data
▪ Data are lost when program is terminated
Department of Mechanical Engineering, BUET 1
File Directed Input Output
▪ Some programs expect the same set of data to be fed as
input every time it is run
• Cumbersome.
• Better if the data are kept in a file, and the program reads
from the file.
▪ Programs generating large volumes of output
• Difficult to view on the screen
• Better to store them in a file for later viewing/ processing
Department of Mechanical Engineering, BUET 2
Real-life applications
▪ Large volume of data
• For example, physical experiments (CERN collider), human
genome, population records, etc.
▪ Need for flexible approach to store/retrieve data
▪ These store/retrieve data operations necessitate the concept of
files
Department of Mechanical Engineering, BUET 3
Files
▪ Files are places on disks where group of related data is
stored.
• Examples are a C program, executable files, word files,
powerpoint files, etc.
▪ High-level programming languages support file
operations
• Naming
• Opening
• Reading
• Writing
• Closing
Department of Mechanical Engineering, BUET 4
Defining and opening file
▪ To store data file in secondary memory (disk) one must
specify to OS:
• Filename (e.g. sort.c, input.data)
• Data structure (e.g. FILE)
• Purpose (e.g. reading, writing, appending)
Department of Mechanical Engineering, BUET 5
Filename
▪ Filename consists of any string of characters that make
up a valid filename for the OS
▪ Filename might contain two parts:
• Primary (given name)
• Optional period with extension (to indicate type)
▪ Examples: a.out, prog.c, temp, text.out, cgpa.txt,
data.in, data.out, letter.docx, etc.
Department of Mechanical Engineering, BUET 6
General syntax for operating with files
FILE *file_pointer_name;
Example: FILE *fp; /*variable fp is pointer to type FILE*/
file_pointer_name = fopen(“filename”, “mode”);
Example: fp = fopen (“input.txt”, “r”);
/*opens file with name input.txt , assigns identifier to fp */
▪ fp
• contains all information about file
• Communication link between system and program
▪ Mode can be
• r open file for reading only;
• w open file for writing only;
• a open file for appending (adding) data
Department of Mechanical Engineering, BUET 7
Different modes
▪ Writing mode
• if file already exists then contents are deleted,
• else new file with specified name created
▪ Appending mode
• if file already exists then file opened with contents safe
• else new file created
▪ Reading mode
• if file already exists then opened with contents safe
• else error occurs.
//File operations with user given filename
//File operation with programmer
FILE *empl ;
//given filenames
char filename[25];
FILE *fp1, *fp2;
printf(“\nEnter input Filename:”);
fp1 = fopen(“data”, ”r”);
scanf (“%s”, filename);
fp2= fopen(“results”, “w”);
empl = fopen (filename, “r”) ;
Department of Mechanical Engineering, BUET 8
File Modes
The types that may be used with fopen function are:
Type Meaning
"r" Open for reading. The file must already exist
“w" Open for writing. It will be created if it does not exist
"a" Open for append (material to the end of existing file)
or a new file will be created
"r+" Open for both reading and writing. File must exist
"w+" Open for both reading and writing. If the file exists its
contents are overwritten
"a+" Open for both reading and appending. If the file does
not exist it will be created
Department of Mechanical Engineering, BUET 9
Closing a file
▪ Several files may be opened at the same time.
▪ All files must be closed as soon as all operations on them are
completed as follows:
fclose(file_pointer1);
fclose(file_pointer2);
…………
▪ Ensures
• Ensures that all file data stored in memory buffers are properly written
to the file.
• All links to file broken
• Accidental misuse of file prevented
▪ If we want to change the mode of file, it is better to first close
the file and open again
Department of Mechanical Engineering, BUET 10
Three Mandatory steps for file operations
FILE *p1, *p2; //step1: declaring a file pointer
p1 = fopen(“INPUT.txt”, “r”); //step2: linking a file pointer
p2 =fopen(“OUTPUT.txt”, “w”);
……..
……..
fclose(p1); //step3: unlinking a file pointer
fclose(p2);
▪ A pointer can be reused after closing [unlinking]
[with the same file or with any other file]
Department of Mechanical Engineering, BUET 11
Input/Output operations on files
C provides several different functions for reading/writing:
▪ getc() – read a character
▪ putc() – write a character
▪ fprintf() – write set of data values with directed formatting
▪ fscanf() – read set of data values from directed formatting
▪ getw() – read integer
▪ putw() – write integer
Department of Mechanical Engineering, BUET 12
fscanf() and fprintf()
▪ Similar to scanf() and printf()
▪ In addition, provide a file-pointer
fscanf ( file_pointer, “control string”, &variables ) ;
fprintf ( file_pointer, “control string”, variables/expression/constants ) ;
▪ For example, given the following
file-pointer f1 (points to file opened in write mode)
file-pointer f2 (points to file opened in read mode)
integer variable i
float variable f
fscanf ( f2, “%d %f”, &i, &f ) ;
fprintf ( f1, “%d %f\n”, i, f);
▪ fscanf() returns EOF when end-of-file reached
Department of Mechanical Engineering, BUET 13
5 steps to be included for file
operations
FILE *p1, *p2; //step1: declaring file pointers
p1 = fopen(“INPUT.txt”, “r”); //step2: opening files
p2 =fopen(“OUTPUT.txt”, “w”);
……..
……..
fscanf ( p1, “%d”, &variable); //step3: getting inputs
fprintf (p2, “%d”, variable); //step4: printing outputs
fclose(p1); //step5: closing file pointers
fclose(p2);
Department of Mechanical Engineering, BUET 14
Example: 3 mandatory steps for file
operations
#include <stdio.h>
int main( )
{
FILE *output; //step-1
output = fopen(“h1.txt”, “w”); //step-2
fprintf (output, “Hello World”); //optional I/O step
fclose(output); //step-3
return 0;
} //output
Output: (No output on the screen)
A file ‘h1.txt’ will be created in the
program folder and output “Hello World”
will be printed in the file.
Department of Mechanical Engineering, BUET 15
Example :: Sorting GPA from an input file
#include <stdio.h>
#define SIZE 10
int main( ) {
int i, k = 0;
float temp, cgpa[SIZE];
FILE *input, *output; //step1
input = fopen("cgpa.txt", "r"); //step2
output = fopen("merit.txt", "w");
for(i = 0; i < SIZE; i++) { fscanf(input, "%f\n", &cgpa[i]);} //step3
i=0;
compare:
for(i = k; i < SIZE; i++){
if (cgpa[k] < cgpa[i+1]) //This input
{ //file named
temp = cgpa[k]; //“cgpa.txt”
cgpa[k] = cgpa[i+1]; //must exist
cgpa[i+1] = temp; //in your
} //program
} //folder
k++;
if(k<SIZE)goto compare;
Department of Mechanical Engineering, BUET 16
Example :: Printing the Sorted GPA to an
output file
fprintf(output, "The CGPA arranged in order of merit as follows:\n");
fprintf(output, "\n Merit\n Position\tCGPA\n\n"); //step4
for(i=0;i<SIZE;i++){fprintf(output, " %d\t\t%4.2f\n", i+1, cgpa[i]);}
fclose(input); //step5
fclose(output);
return 0;
}
// This output file
// named “merit.txt”
// is generated by
// the program in
// your program
// folder
Department of Mechanical Engineering, BUET 17
Example :: Creating Merit list from an input file
#include <stdio.h>
#define SIZE 10 //changing the digits changes the number of array elements
int main()
{
int stdno[SIZE]; //This input
float cgpa[SIZE], temp; //file named
int i=0,j=0,k=0, m, n; //“cgpa1.txt”
FILE *inptr, *outptr; //must exist
inptr = fopen("cgpa1.txt", "r"); //in your
outptr = fopen("merit2.txt", "w"); //program
if(inptr==NULL) //folder
{
goto exit1;
}
for(i=0;i<SIZE;i++)
{
fscanf(inptr, "%d\t%f\n", &stdno[i], &cgpa[i]); //number input
}
Department of Mechanical Engineering, BUET 18
Example :: Creating Merit list from an input file
compare: // a label followed by a colon for using with goto statement
for(i=k; i<SIZE; i++){
if (cgpa[k] < cgpa[i+1])
{
temp = cgpa[k];
cgpa[k] = cgpa[i+1];
cgpa[i+1] = temp;
temp = stdno[k];
stdno[k] = stdno[i+1];
stdno[i+1] = temp;
}
}
k++;
if(k<SIZE)goto compare; // goto statement followed by a label with semi-colon
Department of Mechanical Engineering, BUET 19
Example :: Creating Merit list from an input file
fprintf(outptr,"\n\n\tThe Merit Positions are as follows:\n");
fprintf(outptr,"\n\tStudent\tCGPA\tMerit\n\t No. \t \tPosition\n");
for(j=0;j<SIZE;j++)
{
fprintf(outptr,"\n\t %d\t%4.2f\t %d\n", stdno[j],cgpa[j],j+1); //prints sorted data
}
fprintf(outptr,"\n\n\tThank you for using this program...\n\n\n\n");
fclose(inptr);
fclose(outptr);
goto exit;
exit1:
printf("\n\n\tNo input file found! Aborting...\n\n");
goto exit;
exit:
return 0;
}
Department of Mechanical Engineering, BUET 20
Example :: Creating Merit list from an input file
// This output file
// named “merit2.txt”
// is generated by
// the program in
// your program
// folder
Department of Mechanical Engineering, BUET 21
Let’s Try Developing a C Program
to Select Lottery Winners
Use random( ) functions:
Step1: Include time.h header file
#include <time.h>
Step2: Initialize “srand( seed)” function inside your main( )
function
srand(time(NULL)); //by default srand(1)
Step3: Get random number
int number;
number = rand ( ) % generate random numbers in the range [0, RAND_MAX)
Department of Mechanical Engineering, BUET 22
Let’s Try Developing a C Program
to Select Lottery Winners
❑ srand( seed) function:
▪ The srand() function sets the starting point for producing a series
of pseudo-random integers
▪ If srand() is not called, the rand() seed is set as if srand(1) were
called at the start of the program
▪ Any other value for seed sets the generator to a different starting
point
▪ If seed value in srand() is kept same every time a programs run
then the program will create same sequence of random numbers
using rand() on every program run
Department of Mechanical Engineering, BUET 23
Let’s Try Developing a C Program
to Select Lottery Winners
// This program will create same sequence of
// random numbers on every program run
#include <stdio.h> Output in my laptop
#include <stdlib.h>
int main(void)
{
for(int i = 0; i<5; i++)
printf(" %d ", rand());
printf("\n");
return 0;
}
❑ In the above program, srand(1) were called at the start of the program
❑ Thus, this program will create same sequence of random numbers on
every program run
Department of Mechanical Engineering, BUET 24
Let’s Try Developing a C Program
to Select Lottery Winners
// C program to generate random numbers
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
// Driver program
int main(void)
{
// This program will create different sequence of random numbers on every program run
// Use current time as seed for random generator
srand(time(NULL)); //time(0) will also work
for(int i = 0; i<5; i++)
printf(" %d ", rand()); Output in my laptop
printf("\n");
return 0;
}
Department of Mechanical Engineering, BUET 25
Let’s Try Developing a C Program
to Select Lottery Winners
❑ Generating random number in a range in C:
▪ C does not have a built-in function for generating a number in the
range
▪ However, rand() generates a random number from 0 to RAND_MAX
▪ Using rand(), a random number in range can be generated as,
num = (rand() % (upper – lower + 1)) + lower
int i;
for (i = 0; i < count; i++) {
int num = (rand() % (upper - lower + 1)) + lower;
printf("%d ", num);
}
Department of Mechanical Engineering, BUET 26
Let’s Try Developing a C Program to Select Lottery
Winners
❑ Create a file “lottery.txt” with two columns, one column with serial numbers
1 to 10 and another with lottery numbers of 8 digits (any number)
❑ Start a loop with counter, i = 1; get a random number from 1 to maximum
value of 10.
number = rand ( );
❑ The random number for i = 1 is the champion winner.
❑ Similarly, the random number for i = 2 is the first runner-up and i = 3 is the
second runner-up.
❑ Print your outputs in a file “winners.txt” with two columns, the first column
showing the lottery number and second column showing the positions as
champion, first runner-up and so on.
Department of Mechanical Engineering, BUET 27
Let’s Try Developing a C Program to Select Lottery
Winners
A Sample input file: “lottery.txt”
//must exist in the program folder
Department of Mechanical Engineering, BUET 28
Let’s Try Developing a C Program to Select Lottery Winners
A Sample output file: “winners.txt” //to be generated by the program
Note: check if the program selects different random winners every time it runs!
Home Assignment: write this code. I will create an assignment in
teams; submit it there. Upload a pdf file and the .c file with code.
Department of Mechanical Engineering, BUET 29
Let’s Try another C Program to Randomly Select Students
for Admission
❑ Create a file “appforms.txt” with two columns, one column with serial
numbers 1 to 10 and another with form numbers of 4 digits (any
number)
❑ Start a loop with counter, i = 1; get a random number from 1 to
maximum value of 10.
❑ number = rand ( ) % 11;
❑ The random number for i = 1 is the seat no.1.
❑ Similarly, the random number for i = 2 is for seat no.2, i = 3 is is for
seat no.3 and so on.
❑ Print your outputs in a file “admissions.txt” with two columns, the
first column showing the serial number and second column showing
the seat no.1, seat no.2 and so on.
Department of Mechanical Engineering, BUET 30
Let’s Try Developing a C Program to Randomly
Select Students for Admission
A Sample input file:
“appforms.txt”
//must exist in the program folder
Department of Mechanical Engineering, BUET 31
Let’s Try Developing a C Program to Randomly Select
Students for Admission
A Sample output file: “admissions.txt” //to be generated by the program
Note: check if the program selects different random winners every time it runs!
Department of Mechanical Engineering, BUET 32