Programming Fundamentals
|
|
- Luke Robinson
- 6 years ago
- Views:
Transcription
1 Programming Fundamentals Day 4 1
2 Session Plan Searching & Sorting Sorting Selection Sort Insertion Sort Bubble Sort Searching Linear Search Binary Search File Handling Functions Copyright 2004, 2 2
3 Sorting Techniques Bubble Sort Sorts by comparing adjacent elements and swap whenever required Selection Sort Sorts the array by selecting the first smallest element,putting it in the first position of the array, The second smallest element is put in the second position of the array and so on. Insertion Sort Sorts the array by inserting each element of the array in a existing presorted array of elements Copyright 2004, 3 The sorting refers to the operation of arranging data in some given order, such as increasing or decreasing (with numerical data) or alphabetically (with character data). There are a number of sorting methods Bubble sort, Selection sort, Insertion sort, Heap sort, Quick sort etc.. The particular method one chooses depends on the properties of the data and the operations one may perform on the data. However, we will briefly discuss only on the first three sorting methods implemented for array sorting. 3
4 Bubble Sort Bubble the smallest element up in the list. 1 st pass of the Array 2 nd pass of the Array The pass in which there is no swapping of elements indicates array is sorted Copyright 2004, 4 The sorting method followed in Bubble Sort is: Keep passing through the array, exchanging adjacent elements that are out of order, continuing until the array is sorted. In other word, Bubble up the smallest element to the last location of the array. Implementation of the Bubble Sort is easier than the Insertion or Selection sort. But bubble sort is generally slower than the other two methods. Its is slower because it need to scans through the entire array and swap adjacent elements whenever required. Even the array is sorted number of passes required is one. 4
5 Bubble Sort Program #include <stdio.h> int iread_array_of_numbers(int []); int ibubble_sort(int [], int); int ibubble(int [], int) int main() int inumberofelements,aiarrnumbers[10]; inumberofelements=iread_array_of_numbers(aiarrnumbers); ibubble_sort(iarrnumbers, inumberofelements) ; printf( The Sorted elements are : "); for(iindex = 0; iindex < inumberofelements; iindex++) printf("%d",aiarrnumbers[iindex]); Copyright 2004, 5 The efficiency of the sort methods is calculated as number of moves required to sort the array in the average case and considering only the highest order terms in the result. The number of moves required for sorting an array using the Bubble Sort is of the order of n 2. 5
6 Bubble Sort Program- (Contd..) /* Function to sort elements of an array using Bubble Sort */ int ibubble_sort(int aiarr[], int inoelements) int iindex, ivalue; for(iindex = inoelements - 1; iindex > 0; iindex-- ) ivalue = ibubble(aiarr, iindex); if( ivalue == 0) break; Copyright 2004, 6 6
7 Bubble Sort Program-(Contd..) int ibubble(int aiarr[], int ilast) int iindex, iswap; iswap = 0; for(iindex = 0; iindex < ilast; iindex++) if ( aiarr[iindex] > aiarr[iindex + 1] ) swap(aiarr, iindex, iindex + 1); iswap = iswap +1; return(iswap); Copyright 2004, 7 7
8 Selection Sort The next smallest value must be found and placed in order. find the smallest element in the array exchange it with the element in the first position find the second smallest element exchange it with the element in the second position Copyright 2004, 8 Lets us look at sorting as follows. First the smallest array element is identified. This is swapped with the first element of the array Second the next smallest element is identified and this is swapped with the second element of the array. This process continues till all the elements of the array are put in order. Since the technique involves selecting the minimum element its called selection sort 8
9 Selection Sort Algorithm : Find the position p, and the value a[p], of the smallest element in the unsorted array; Swap the element at a[p] with the element at the first position of the unsorted part of the array. Copyright 2004, 9 9
10 Selection Sort ia[0] 1 ia[1] 4 ia[2] 9 ia[3] 7 ia[4] 8 ia[5] 10 Ia[0] Ia[1] Ia[2] Ia[3] Ia[4] Ia[1] Ia[2] Ia[3] Ia[4] Copyright 2004, 10 10
11 Selection Sort Ia[0] Ia[1] Ia[2] Ia[3] Ia[4] Ia[5] Ia[0] Ia[1] Ia[2] Ia[3] Ia[4] Ia[5] Ia[0] Ia[1] Ia[2] Ia[3] Ia[4] Ia[5] Copyright 2004, 11 11
12 Selection Sort #include <stdio.h> int iread_array_of_numbers(int [ ]); void vselection_sort(int [ ], int); int iminimum_in_an_array(int [ ], int, int); int iswap_elements(int [ ], int, int); void main( ) int inumberofelements, aiarrnumbers[10],iindex; inumberofelements = iread_array_of_numbers(aiarrnumbers); iselection_sort(aiarrnumbers, inumberofelements) ; printf( The Sorted elements are : "); for(iindex = 0; iindex < inumberofelements; iindex++) printf("%d", iarrnumbers[iindex]); Copyright 2004, 12 12
13 Selection Sort /* Function to sort elements of an array using Selection Sort */ void vselection_sort(int aiarr[ ], int inoelements) int iindex; int ipos; for(iindex = 0; iindex < inoelements - 1; iindex++) ipos = iminimum_in_an_array(iarr, iindex, inoelements -1); iswap_elements(iarr, iindex, ipos); Copyright 2004, 13 A disadvantage of selection sort is that the user of this method might be surprised to find that it takes about as long to sort an already ordered array as it does for an unordered array! The number of moves required for sorting an array using the Selection Sort is of the order of n 2. 13
14 Insertion Sort Compare the first two elements of the array and swap them so that they are in place Now take the third element and insert in place within the presorted array on 2 elements Repeat this process till you reach the end of the array Copyright 2004, 14 14
15 Insertion Sort Insert the next element into the correct position of the ordered part and, in the process, extend the ordered section by one element. Algorithm : 1. Find the minimum and put it in place to act as sentinel. 2. While there are still elements to be inserted in the ordered part do : a) select next element x to be inserted b) while x is less than preceding element do b.1) move preceding element up one position, b.2) extend search back one element further; c) insert x at current position Copyright 2004, 15 Insertion sort works by considering the elements one at a time and inserting the element in its proper place among those already considered. In other word, the (i+1) th element K[i] is inserted into its rightful place among K[0], K[1],, K[i - 1 ], which are previously placed in a sorted order. 15
16 Insertion Sort Program #include <stdio.h> int iread_array_of_numbers(int []); int iinsertion_sort(int [ ], int); int main( ) int inumberofelements, aiarrnumbers[10]; inumberofelements=iread_array_of_numbers(aiarrnumbers); iinsertion_sort(aiarrnumbers, inumberofelements) ; printf( The Sorted elements are : "); for(iindex = 0; iindex < inumberofelements; iindex++) printf("%d", aiarrnumbers[iindex]); Copyright 2004, 16 16
17 Insertion Sort Program /* Function to sort elements of an array using Insertion Sort */ int iinsertion_sort(int aiarr[], int inoelements) int iindex; int ipos; for(iindex = 1; iindex < inoelements; iindex++)..;..; return(1); Copyright 2004, 17 17
18 Which Sorting algo. to use Factors that help in deciding the sorting algorithm to be used are +Memory +Performance +Flexibility +Concise code Copyright 2004, 18 While deciding upon which sorting algorithm to be used there are several things that need to be considered. Number of comparisons and swaps have a direct impact on the performance of the code Bubble sort is the simplest to use and implement but here the #of comparisons and swaps are more which results in poor performance is the array size is large. The bubble sort algorithm has a provision to stop once array is sorted.the selection sort, on the other hand, always needs to go through the same amount of work regardless of the data The insertion sort is a little better and whilst it cannot detect that it has finished sorting, the logic of the algorithm means that it comes to a rapid conclusion when dealing with sorted data. 18
19 Searching Heavily used in production programming Efficiency is a must Lot of techniques available that work on sorted or unsorted arrays. Some of the techniques are Linear Search Binary Search Copyright 2004, 19 Values stored in arrays often need to be queried. Searching techniques play a important role here 19
20 Linear Search Compare the search value with each and every element of the array till a match is found Stop comparison once match is found or you reach the end of the array Search value is compared with 10 and then 5 since the match is found no further comparisons carried out Search value is compared with 12,5,23,35. But no match is found. However the end of array has reached without a match so no further comparisons Copyright 2004, 20 Consider a array of 4 values. In Linear Search, as the number of elements increases, the time taken to perform the search increases linearly. The linear search requires n comparisons in the worst case (i.e., when the elements of the array are in the reverse order of sorting). 20
21 Linear Search # include <stdio.h> int iread_array_of_numbers(int []); int ilinear_search(int [ ], int, intt); int main( ) int ipos, inumberofelements, ielementtobesearched, aiarrnumbers[10]; inumberofelements=iread_array_of_numbers(iarrnumbers); printf ( Enter the element to be searched for : ); scanf( %d, &ielementtobesearched); ipos = ilinear_search (aiarrnumbers, inumberofelements, ielementtobesearched) ; if (iposofelement >= 0) printf("element is present at %d", ipos); else printf("element is not present "); Copyright 2004, 21 21
22 Linear Search /* Function to search for an element in an array using Linear Search */ int ilinear_search(int aiarr[], int inoelements, int inumbertobesearched) int ifound, iindex, ifound = 0; for(iindex = 0; iindex < n; iindex ++ ) if (aiarr[iindex] == inumbertobesearched) ifound =1; break; if (ifound == 0) return -1; else return iindex; Copyright 2004, 22 The array is aiarr[] is passed using pass by reference mechanism to the function 22
23 Binary Search #include <stdio.h> int iread_array_of_numbers(int aiarr[ ]); int ibinary_search(int aiarr[ ], int inoelements, int isearchelement); int main() int iposofelement, inumberofelements,ielementtobesearched,aiarrnumbers[10]; inumberofelements=iread_array_of_numbers(iarrnumbers); printf ( Enter the element to be searched for : ); scanf( %d, &ielementtobesearched); iposofelement = ibinary_search(iarrnumbers, inumberofelements,ielementtobesearched) ; if (iposofelement >= 0) printf("element is present at %d", iposofelement); else printf("element is not present "); Copyright 2004, 23 Binary search works by comparing your search element with the center element of the array. Depending on whether the search element is greater or less than the middle element we now consider second half or the first half of the array and repeat the procedure The Binary search algorithm is given below. Arr is an ordered Array of N elements. skey is the key element to be searched for. Low, Middle and High denote the lower, middle and upper limits of the search interval, respectively. Algorithm Start Step 1 : Low = 1 Step 2 : High = N -1 Step 3 : Repeat Step 4 to Step 5 While Low <= High Step 4 : Middle = (Low + High) / 2 Step 5 : If ( Arr[Middle] = skey) Then WRITE successful search Stop Else If ( skey < Arr[Middle] ) Then High = Middle - 1 End-If Else Low = Middle + 1 End-If Step 6 : WRITE unsuccessful search End Since the searching algorithm works by continuously dividing your array into two parts, in the worst case binary search will require log 2 N comparisons to search an element in an array of size N. 23
24 Binary Search /* Function to search for an element in an array using binary search */ int ibinary_search(int aiarr[], int inoelements, int inumbertobesearched) int ilowpos, ihighpos, imidpos,ilowpos = 0; ihighpos = inoelements -1; while (ihighpos >= ilowpos) imidpos = (ilowpos + ihighpos)/2; if (iarr[imidpos] == inumbertobesearched) return imidpos; else if (iarr[imidpos] < inumbertobesearched) ilowpos = imidpos + 1; else ihighpos = imidpos -1; return -1; Copyright 2004, 24 In the array implementation of Linear Search, we can improve significantly the search time if the array is already ordered by using a search method known as Binary Search. 24
25 /*Read the data into the array*/ int iread_array_of_numbers(int aiarr[ ]) int inumber; inumber =0; Choice = y ; while(choice == Y Choice == y ) printf( \n Enter the %d element, inumber + 1); fflush(stdin); scanf( %d, &aiarr[inumber - 1]); inumber = inumber + 1; printf( \ndo you want to continue: enter (y/n) ); fflush(stdin); scanf( %c,&choice); Copyright 2004, 25 25
26 I/O Streams in C File handling in C is provided by a number of functions in the standard library. All input/output is based on the concept of a stream. There are two types of stream: text stream binary stream A text stream is a sequence of characters composed into lines, each line is terminated with a newline (\n) character. A binary stream is a sequence of unprocessed bytes - newline has no significance. Copyright 2004, 26 26
27 File Handling Functions in C Basic operations to be carried out on files 1. Opening of file 2. Closing of file 3. Reading file 4. Writing file 5. Traversing the pointer 6. Checking for end of file 7. Get the current position in file For all the file handling operations the pointer to file is created which is of the data type :- FILE pointer data type defined in stdio.h Eg. FILE *fp; Copyright 2004, 27 File access in C is achieved by associating a stream with a file. FILE *in; The fopen function is used to open the file. Files may be opened in a number of modes, as shown in the following table. File Modes Operator r w overwritten. a to the end of the file. Description Open a text file for reading. Create a text file for writing. If the file exists, it is Open a text file in append mode. Text is added r+ Open a text file for reading and writing. w+ Create a text file for reading and writing. If the file exists, it is overwritten. a+ - Open a text file for reading and writing at the end. The update modes are used with fseek, fsetpos and rewind functions. The fopen function returns a file pointer, or NULL if an error occurs. The following example opens a file called junk.txt in read-only mode. It is good programming practice to test the file exists. if ((in = fopen("junk.txt", "r")) == NULL) puts("unable to open the file"); return 0; Files are closed using the fclose function. fclose(in); The feof function is used to test for the end of the file. The functions fgetc, fscanf, and fgets are used to read data from the file. The following example lists the contents of a file on the screen, using fgetc to read the file a character at a time. 27
28 Opening File fopen() - opens a file in the mode specified Prototype declaration FILE *fopen( filename mode ); Read mode Write Mode Append Mode Read Write Mode Write Read Mode Append,Read-Write Mode r w a a+ w+ a+ Opens file for reading purposes, File has to exist Opens file for writing purposes, File is recreated Opens file for writing purposes, File is not recreated if it exists Opens file for reading+writing purposes, File has to exist. Existing data can be modified, new data cannot be added Opens the file for r+w purposes. File is recreated Opens the file for read+write+append mode Copyright 2004, 28 Your program must open a file before it can access it. This is done using the fopen function, which returns the required file pointer. If the file cannot be opened for any reason then the value NULL will be returned. You will usually use fopen as follows if ((output_file = fopen("output_file", "w")) == NULL) fprintf(stderr, "Cannot open %s\n", "output_file");fopen takes two arguments, both are strings, the first is the name of the file to be opened, the second is an access character, which is usually one from the above table 28
29 Examples of fopen calls FILE *fp1, *fp2, *fp3; char filename[32]; /*open existing file for reading*/ fp1=fopen( mydatafile, r ); /*open to write - if file exists it is overwritten */ fp2=fopen( results, w ); printf( Name of output file: ); scanf( %s, filename); /*append to existing file or create new file */ fp3=fopen(filename, a ); Copyright 2004, 29 29
30 Closing File fclose() - opens a file in the mode specified Prototype declaration int fclose(file *); Copyright 2004, 30 The fclose command can be used to disconnect a file pointer from a file. This is usually done so that the pointer can be used to access a different file. Systems have a limit on the number of files which can be open simultaneously, so it is a good idea to close a file when you have finished using it. This would be done using a statement like fclose(output_file); If files are still open when a program exits, the system will close them for you. However it is usually better to close the files properly. The function fclose is used to close the file i.e. indicate that we are finished processing this file. We could reuse the file pointer fp by opening another file. Always remember to close a file before reopening the file in any other mode. 30
31 Formatted Input/Output The functions fscanf and fprintf provide the equivalent for any open file. Their prototypes: int fscanf(file *fp, char *format, arg1, arg2,...); int fprintf(file *fp, char *format, arg1, arg2,...); For Exmaple input an integer and a float from file *fp1 fscanf(fp1, %d%f, &x, &y); output to file * fp2 fprintf(fp2, Final total was %d, total); Copyright 2004, 31 The fscanf and fprintf function work in a similar manner as scanf and printf. Arguments to fscanf are in addition to the format stirng and the variable list, pointer to the file from which read operation needs to be done. Arguments to printf are in addition to the format stirng and the variable list, pointer to the file on which write operation needs to be done. Some more file I/O functions fgets fputs fgetc fputc 31
32 Character / String Input char *fgets (char *s, int n, FILE *fp); char *gets(char *s); fgets reads characters into the array s, from file * fp until a newline or n-1 characters have been read It returns NULL if an error or EOF occurs. fgets retains any newline characters gets does not make sure the character array s is large enough to hold all the data being read! fgets is quite useful when you don't know how many lines a file contains keep reading line-by-line it returns NULL then use sscanf(char * s, char *format, arg1, arg2,...) to break a string s into parts sscanf(line, "%s %d", name, &age); breaks line into a string variable name and integer variable age Copyright 2004, 32 The Standard I/O Library provides similar routines for file I/O to those used for standard I/O. The routine getc(fp) is similar to getchar() and putc(c,fp) is similar to putchar(c). Thus the statement c = getc(fp); reads the next character from the file referenced by fp and the statement putc(c,fp); writes the character c into file referenced by fp /* file.c: Display contents of a file on screen */ #include <stdio.h> void main() FILE *fp; int c ; fp = fopen( prog.c, r ); c = getc( fp ) ; while ( c!= EOF ) fclose( fp ); putchar( c ); c = getc ( fp ); In this program, we open the file prog.c for reading. We then read a character from the file. This file must exist for this program to work. If the file is empty, we are at the end, so getc returns EOF a special value to indicate that the end of file has been reached. (Normally -1 is used for EOF).The while loop simply keeps reading characters from the file and displaying them, until the end of the file is reached. 32
33 File input example char line[50], name[30]; int age; FILE * fp; fp = fopen("names.txt", "r"); if (fp!= NULL) while (fgets(line, 49, fp)!= NULL) sscanf(line, "%s %d", name, &age); printf("name is %s, age is %d\n", name, age); printf("end of file"); Copyright 2004, 33 Names.txt is a file already created using a text editor. Each line in the file contains a name followed by an integer age. 33
34 Simple Example Code #include <stdio.h> main () FILE *fp1,*fp2,*fp3; char filename[32]; char result[30]=""; int letter; fp1 = fopen("mydata.txt","r"); fp2 = fopen("results.txt","w"); printf("name of output file: "); scanf("%s",filename); fp3= fopen(filename,"a"); fgets(result, 12, fp1); printf("the first file contains: %s", result); fputs(result,fp2); letter='a'; fputc(letter,fp3); fclose(fp1);fclose(fp2);fclose(fp3); Copyright 2004, 34 Some more examples #include <stdio.h> int main() FILE *in; int key; if ((in = fopen("junk.txt", "r")) == NULL) puts("unable to open the file"); return 0; while (!feof(in)) key = fgetc(in); /* The last character read is the end of file marker */ /* so don't print it */ if (!feof(in)) putchar(key); fclose(in); return 0; 34
35 Some More Examples #include <stdio.h> #include <stdlib.h> int m ain() int num ; char buffer[20]; printf("enter a num ber: "); /* Use the fgets function to validate input */ fgets(buffer, 20, stdin); num = atoi(buffer); printf("the num ber you entered was % d\n", num ); return 0; #include <stdio.h> int m ain() FILE *in, *out; int key; if ((in = fopen("junk.txt", "r")) == NULL) puts("unable to open the file"); return 0; out = fopen("copy.txt", "w"); while (!feof(in)) key = fgetc(in); if (!feof(in)) fputc(key, out); fclose(in); fclose(out); return 0; Copyright 2004, 35 35
36 File Functions : Used in Project int fiopenfile(int ifile) int fireadfile (char acline[ ], int ifile, int ipos) void fvwritefile (char acline[ ], int ifile) int fiupdatefile (char acline[ ], int ifile) int ficlosefile (int ifile) Copyright 2004, 36 36
37 File open: fiopenfile Prototype : int fiopenfile(int ifile) Parameters : ifile- integer :-» DEP_FILE to open dept.txt,» EMP_FILE to open emp.txt. e.g., int fiopenfile(dep_file) Return value: The function returns 1 on success and 0 on failure. Remarks : The function opens the file as specified in the ifile argument. This function should be used only once at the beginning of the program. Copyright 2004, 37 37
38 Read file : fireadfile Prototype : int fireadfile ( char acline[ ], int ifile, int ipos) Parameters : acline - A string: The string that is read from the file. ifile - integer :» DEP_FILE to read dept.txt» EMP_FILE to read emp.txt ipos - integer :» BEGIN to read from the beginning.» CURRENT to read from the current position. Return value: The function returns 1 on success and 0 on failure. Remarks : The function reads a line into acline from the file that specified by ifile argument. If ipos is BEGIN it reads from the first line. If ipos is CURRENT it reads the line from current-position. Copyright 2004, 38 38
39 Write file : fvwritefile Prototype: void fvwritefile (char acline[ ], int ifile) Parameters : acline - A string: The string that is written into the file. ifile - integer : DEP_FILE to open dept.txt, EMP_FILE to open emp.txt. Return value: none. Remarks : The function writes a line as in argument acline into the file that specified by ifile argument. Copyright 2004, 39 39
40 Update file : fiupdatefile Prototype: int fiupdatefile (char acline[ ], int ifile) Parameters : acline - A string: The string that is written into the file. ifile - integer : DEP_FILE to open dept.txttxt, EMP_FILE to open emp.txt. Return value: The function returns 1 on success and 0 on failure. Remarks : The function updates a line in the file as specified by ifile argument. The string as in argument sline will replace the line. It will be the line, which is last read from the file by fireadfile function. Copyright 2004, 40 40
41 Close file: ficlosefile Prototype: int ficlosefile (int ifile) Parameters : ifile - integer : DEP_FILE to open dept.txt, EMP_FILE to open emp.txt. Return value: The function returns 1 on success and 0 on failure. Remarks: The function closes the file. Copyright 2004, 41 41
42 Summary Various sorting and searching methods Basic operations of opening, reading/writing and closing file Copyright 2004, 42 42
43 Thank You! Copyright 2004, 43 43
Standard File Pointers
1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf
More informationFile I/O. Arash Rafiey. November 7, 2017
November 7, 2017 Files File is a place on disk where a group of related data is stored. Files File is a place on disk where a group of related data is stored. C provides various functions to handle files
More informationMode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.
Files Files enable permanent storage of information C performs all input and output, including disk files, by means of streams Stream oriented data files are divided into two categories Formatted data
More informationDarshan Institute of Engineering & Technology for Diploma Studies Unit 6
1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard
More informationFile IO and command line input CSE 2451
File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to
More informationIO = Input & Output 2
Input & Output 1 IO = Input & Output 2 Idioms 3 Input and output in C are simple, in theory, because everything is handled by function calls, and you just have to look up the documentation of each function
More informationUnit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character
1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard
More informationC Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;
C Input/Output Before we discuss I/O in C, let's review how C++ I/O works. int i; double x; cin >> i; cin >> x; cout
More informationCS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files
CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as
More information7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA
7/21/2014 1 FILE INPUT / OUTPUT Dong-Chul Kim BioMeCIS CSE @ UTA What s a file? A named section of storage, usually on a disk In C, a file is a continuous sequence of bytes Examples for the demand of a
More informationC for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing
Chapter 14: File Processing Files and Streams C views each file simply as a sequential stream of bytes. It ends as if there is an end-of-file marker. The data structure FILE, defined in stdio.h, stores
More informationUNIT IV-2. The I/O library functions can be classified into two broad categories:
UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known
More informationIntroduction to file management
1 Introduction to file management Some application require input to be taken from a file and output is required to be stored in a file. The C language provides the facility of file input-output operations.
More informationContent. Input Output Devices File access Function of File I/O Redirection Command-line arguments
File I/O Content Input Output Devices File access Function of File I/O Redirection Command-line arguments UNIX and C language C is a general-purpose, high-level language that was originally developed by
More informationInput / Output Functions
CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain
More informationEM108 Software Development for Engineers
EE108 Section 4 Files page 1 of 14 EM108 Software Development for Engineers Section 4 - Files 1) Introduction 2) Operations with Files 3) Opening Files 4) Input/Output Operations 5) Other Operations 6)
More informationEngineering program development 7. Edited by Péter Vass
Engineering program development 7 Edited by Péter Vass Functions Function is a separate computational unit which has its own name (identifier). The objective of a function is solving a well-defined problem.
More informationFile Access. FILE * fopen(const char *name, const char * mode);
File Access, K&R 7.5 Dealing with named files is surprisingly similar to dealing with stdin and stdout. Start by declaring a "file pointer": FILE *fp; /* See Appendix B1.1, pg. 242 */ header
More informationCE Lecture 11
Izmir Institute of Technology CE - 104 Lecture 11 References: - C: A software Engineering Approach 1 In this course you will learn Input and Output Sorting Values 2 Input and Output Opening and Closing
More informationFiles. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.
File IO part 2 Files Programs and data are stored on disk in structures called files Examples a.out binary file lab1.c - text file term-paper.doc - binary file Overview File Pointer (FILE *) Standard:
More informationAccessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts
Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationQuick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.
1 Quick review of previous lecture Ch6 Structure Ch7 I/O EECS2031 Software Tools C - Structures, Unions, Enums & Typedef (K&R Ch.6) Structures Basics: Declaration and assignment Structures and functions
More informationInput/Output and the Operating Systems
Input/Output and the Operating Systems Fall 2015 Jinkyu Jeong (jinkyu@skku.edu) 1 I/O Functions Formatted I/O printf( ) and scanf( ) fprintf( ) and fscanf( ) sprintf( ) and sscanf( ) int printf(const char*
More informationLecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments
Lecture 7: Files opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments Lecture 5: Files, I/O 0IGXYVI*MPIW 0 opening/closing files reading/writing
More informationSystem Software Experiment 1 Lecture 7
System Software Experiment 1 Lecture 7 spring 2018 Jinkyu Jeong ( jinkyu@skku.edu) Computer Systems Laboratory Sungyunkwan University http://csl.skku.edu SSE3032: System Software Experiment 1, Spring 2018
More informationC How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.
C How to Program, 6/e Storage of data in variables and arrays is temporary such data is lost when a program terminates. Files are used for permanent retention of data. Computers store files on secondary
More informationFiles and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060
CS 2060 Files and Streams Files are used for long-term storage of data (on a hard drive rather than in memory). Files and Streams Files are used for long-term storage of data (on a hard drive rather than
More informationC programming basics T3-1 -
C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of
More informationStandard C Library Functions
Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of
More informationM.CS201 Programming language
Power Engineering School M.CS201 Programming language Lecture 16 Lecturer: Prof. Dr. T.Uranchimeg Agenda Opening a File Errors with open files Writing and Reading File Data Formatted File Input Direct
More informationData File and File Handling
Types of Disk Files Data File and File Handling Text streams are associated with text-mode files. Text-mode files consist of a sequence of lines. Each line contains zero or more characters and ends with
More informationPROGRAMMAZIONE I A.A. 2017/2018
PROGRAMMAZIONE I A.A. 2017/2018 INPUT/OUTPUT INPUT AND OUTPUT Programs must be able to write data to files or to physical output devices such as displays or printers, and to read in data from files or
More informationLecture 9: File Processing. Quazi Rahman
60-141 Lecture 9: File Processing Quazi Rahman 1 Outlines Files Data Hierarchy File Operations Types of File Accessing Files 2 FILES Storage of data in variables, arrays or in any other data structures,
More informationOrganization of a file
File Handling 1 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example: Consider keeping students records 100 students
More informationFundamentals of Programming. Lecture 15: C File Processing
1 Fundamentals of Programming Lecture 15: C File Processing Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department The lectures of this course
More information25.2 Opening and Closing a File
Lecture 32 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 32: Dynamically Allocated Arrays 26-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor:
More informationCS240: Programming in C
CS240: Programming in C Lecture 13 si 14: Unix interface for working with files. Cristina Nita-Rotaru Lecture 13/Fall 2013 1 Working with Files (I/O) File system: specifies how the information is organized
More informationCSI 402 Lecture 2 Working with Files (Text and Binary)
CSI 402 Lecture 2 Working with Files (Text and Binary) 1 / 30 AQuickReviewofStandardI/O Recall that #include allows use of printf and scanf functions Example: int i; scanf("%d", &i); printf("value
More information2009 S2 COMP File Operations
2009 S2 COMP1921 9. File Operations Oliver Diessel odiessel@cse.unsw.edu.au Last updated: 16:00 22 Sep 2009 9. File Operations Topics to be covered: Streams Text file operations Binary file operations
More informationChapter 12. Files (reference: Deitel s chap 11) chap8
Chapter 12 Files (reference: Deitel s chap 11) 20061025 chap8 Introduction of File Data files Can be created, updated, and processed by C programs Are used for permanent storage of large amounts of data
More informationProgramming in C. Session 8. Seema Sirpal Delhi University Computer Centre
Programming in C Session 8 Seema Sirpal Delhi University Computer Centre File I/O & Command Line Arguments An important part of any program is the ability to communicate with the world external to it.
More informationInput/Output: Advanced Concepts
Input/Output: Advanced Concepts CSE 130: Introduction to Programming in C Stony Brook University Related reading: Kelley/Pohl 1.9, 11.1 11.7 Output Formatting Review Recall that printf() employs a control
More informationCMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.
CMPE-013/L Outline File Processing File I/O Gabriel Hugh Elkaim Winter 2014 Files and Streams Open and Close Files Read and Write Sequential Files Read and Write Random Access Files Read and Write Random
More informationfopen() fclose() fgetc() fputc() fread() fwrite()
The ability to read data from and write data to files is the primary means of storing persistent data, data that does not disappear when your program stops running. The abstraction of files that C provides
More informationUNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.
UNIT-V Unit-5 File Streams Formatted I/O Preprocessor Directives Printf Scanf A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage
More informationC Programming Language
C Programming Language File Input/Output Dr. Manar Mohaisen Office: F208 Email: manar.subhi@kut.ac.kr Department of EECE Review of the Precedent Lecture Arrays and Pointers Class Objectives What is a File?
More informationSAE1A Programming in C. Unit : I - V
SAE1A Programming in C Unit : I - V Unit I - Overview Character set Identifier Keywords Data Types Variables Constants Operators SAE1A - Programming in C 2 Character set of C Character set is a set of
More informationComputer Programming: Skills & Concepts (CP) Files in C
CP 20 slide 1 Tuesday 21 November 2017 Computer Programming: Skills & Concepts (CP) Files in C Julian Bradfield Tuesday 21 November 2017 Today s lecture Character oriented I/O (revision) Files and streams
More informationComputer Programming Unit v
READING AND WRITING CHARACTERS We can read and write a character on screen using printf() and scanf() function but this is not applicable in all situations. In C programming language some function are
More informationC-Refresher: Session 10 Disk IO
C-Refresher: Session 10 Disk IO Arif Butt Summer 2017 I am Thankful to my student Muhammad Zubair bcsf14m029@pucit.edu.pk for preparation of these slides in accordance with my video lectures at http://www.arifbutt.me/category/c-behind-the-curtain/
More informationTopic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)
Topic 8: I/O Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional) No C language primitives for I/O; all done via function
More informationBIL 104E Introduction to Scientific and Engineering Computing. Lecture 12
BIL 104E Introduction to Scientific and Engineering Computing Lecture 12 Files v.s. Streams In C, a file can refer to a disk file, a terminal, a printer, or a tape drive. In other words, a file represents
More informationC mini reference. 5 Binary numbers 12
C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char
More informationFile (1A) Young Won Lim 11/25/16
File (1A) Copyright (c) 2010-2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version
More informationComputer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010
Computer Programming: Skills & Concepts (CP1) Files in C 18th November, 2010 CP1 26 slide 1 18th November, 2010 Today s lecture Character oriented I/O (revision) Files and streams Opening and closing files
More informationSystems Programming. 08. Standard I/O Library. Alexander Holupirek
Systems Programming 08. Standard I/O Library Alexander Holupirek Database and Information Systems Group Department of Computer & Information Science University of Konstanz Summer Term 2008 Last lecture:
More informationPointers and File Handling
1 Pointers and File Handling From variables to their addresses Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 2 Basics of Pointers INDIAN INSTITUTE OF TECHNOLOGY
More informationHIGH LEVEL FILE PROCESSING
HIGH LEVEL FILE PROCESSING 1. Overview The learning objectives of this lab session are: To understand the functions used for file processing at a higher level. o These functions use special structures
More informationComputer programming
Computer programming "He who loves practice without theory is like the sailor who boards ship without a ruder and compass and never knows where he may cast." Leonardo da Vinci T.U. Cluj-Napoca - Computer
More informationC Basics And Concepts Input And Output
C Basics And Concepts Input And Output Report Working group scientific computing Department of informatics Faculty of mathematics, informatics and natural sciences University of Hamburg Written by: Marcus
More information8. Characters, Strings and Files
REGZ9280: Global Education Short Course - Engineering 8. Characters, Strings and Files Reading: Moffat, Chapter 7, 11 REGZ9280 14s2 8. Characters and Arrays 1 ASCII The ASCII table gives a correspondence
More informationAdvanced C Programming Topics
Introductory Medical Device Prototyping Advanced C Programming Topics, http://saliterman.umn.edu/ Department of Biomedical Engineering, University of Minnesota Operations on Bits 1. Recall there are 8
More informationFundamentals of Programming & Procedural Programming
Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Seven: Strings and Files Name: First Name: Tutor: Matriculation-Number: Group-Number:
More informationCSCI 171 Chapter Outlines
Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures
More informationFundamentals of Programming. Lecture 10 Hamed Rasifard
Fundamentals of Programming Lecture 10 Hamed Rasifard 1 Outline File Input/Output 2 Streams and Files The C I/O system supplies a consistent interface to the programmer independent of the actual device
More informationContents. A Review of C language. Visual C Visual C++ 6.0
A Review of C language C++ Object Oriented Programming Pei-yih Ting NTOU CS Modified from www.cse.cuhk.edu.hk/~csc2520/tuto/csc2520_tuto01.ppt 1 2 3 4 5 6 7 8 9 10 Double click 11 12 Compile a single source
More informationDay14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15
Day14 A Young W. Lim 2017-12-26 Tue Young W. Lim Day14 A 2017-12-26 Tue 1 / 15 Outline 1 Based on 2 C Strings (1) Characters and Strings Unformatted IO Young W. Lim Day14 A 2017-12-26 Tue 2 / 15 Based
More informationCh 11. C File Processing (review)
Ch 11 C File Processing (review) OBJECTIVES To create, read, write and update files. Sequential access file processing. Data Hierarchy Data Hierarchy: Bit smallest data item Value of 0 or 1 Byte 8 bits
More informationCS1003: Intro to CS, Summer 2008
CS1003: Intro to CS, Summer 2008 Lab #07 Instructor: Arezu Moghadam arezu@cs.columbia.edu 6/25/2008 Recap Pointers Structures 1 Pointer Arithmetic (exercise) What do the following return? given > char
More informationAnnouncements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays
Strings and Pointers Announcements Lab 4 Why are you taking this course? Lab 5 #, 8: Reading in data from file using fscanf Quiz Quiz Strings Special character arrays End in null character, \ char hi[6];
More informationLab # 4. Files & Queues in C
Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4010: Lab # 4 Files & Queues in C Eng. Haneen El-Masry October, 2013 2 FILE * Files in C For C File I/O you need
More informationCMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program
CMPT 102 Introduction to Scientific Computer Programming Input and Output Janice Regan, CMPT 102, Sept. 2006 0 Your first program /* My first C program */ /* make the computer print the string Hello world
More informationThis code has a bug that allows a hacker to take control of its execution and run evilfunc().
Malicious Code Insertion Example This code has a bug that allows a hacker to take control of its execution and run evilfunc(). #include // obviously it is compiler dependent // but on my system
More informationFile Handling. Reference:
File Handling Reference: http://www.tutorialspoint.com/c_standard_library/ Array argument return int * getrandom( ) static int r[10]; int i; /* set the seed */ srand( (unsigned)time( NULL ) ); for ( i
More informationFile I/O. Preprocessor Macros
Computer Programming File I/O. Preprocessor Macros Marius Minea marius@cs.upt.ro 4 December 2017 Files and streams A file is a data resource on persistent storage (e.g. disk). File contents are typically
More informationChapter 10. File Processing 248 FILE PROCESSING
Chapter 10 FILE PROCESSING LEARNING OBJECTIVES After reading this chapter the reader will be able to understand the need of data file. learn the operations on files. use different data input/output functions
More informationENG120. Misc. Topics
ENG120 Misc. Topics Topics Files in C Using Command-Line Arguments Typecasting Working with Multiple source files Conditional Operator 2 Files and Streams C views each file as a sequence of bytes File
More informationCourse organization. Course introduction ( Week 1)
Course organization Course introduction ( Week 1) Code editor: Emacs Part I: Introduction to C programming language (Week 2-9) Chapter 1: Overall Introduction (Week 1-3) Chapter 2: Types, operators and
More informationProgram Design (II): Quiz2 May 18, 2009 Part1. True/False Questions (30pts) Part2. Multiple Choice Questions (40pts)
Class: No. Name: Part1. True/False Questions (30pts) 1. Function fscanf cannot be used to read data from the standard input. ANS: False. Function fscanf can be used to read from the standard input by including
More informationCS246 Spring14 Programming Paradigm Files, Pipes and Redirection
1 Files 1.1 File functions Opening Files : The function fopen opens a file and returns a FILE pointer. FILE *fopen( const char * filename, const char * mode ); The allowed modes for fopen are as follows
More informationC Programming 1. File Access. Goutam Biswas. Lect 29
C Programming 1 File Access C Programming 2 Standard I/O So far all our I/O operations are read from the standard input (stdin - keyboard) and write to the standard output (stdout - VDU) devices. These
More informationIntroduction to C Recursion, sorting algorithms, files
Introduction to C Recursion, sorting algorithms, files Teil I. recursion TU Bergakademie Freiberg INMO M. Brändel 2018-10-23 1 RECURSION Recursion in programming is a way of solving a problem, by solving
More informationC PROGRAMMING. Characters and Strings File Processing Exercise
C PROGRAMMING Characters and Strings File Processing Exercise CHARACTERS AND STRINGS A single character defined using the char variable type Character constant is an int value enclosed by single quotes
More informationChapter 11 File Processing
1 Chapter 11 File Processing Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 11 File Processing Outline 11.1 Introduction 11.2 The Data Hierarchy 11.3
More informationCopyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 18 I/O in C Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented
More informationC File Processing: One-Page Summary
Chapter 11 C File Processing C File Processing: One-Page Summary #include int main() { int a; FILE *fpin, *fpout; if ( ( fpin = fopen( "input.txt", "r" ) ) == NULL ) printf( "File could not be
More informationLecture6 File Processing
1 Lecture6 File Processing Dr. Serdar ÇELEBİ 2 Introduction The Data Hierarchy Files and Streams Creating a Sequential Access File Reading Data from a Sequential Access File Updating Sequential Access
More informationFile Handling. 21 July 2009 Programming and Data Structure 1
File Handling 21 July 2009 Programming and Data Structure 1 File handling in C In C we use FILE * to represent a pointer to a file. fopen is used to open a file. It returns the special value NULL to indicate
More informationProgramming. Functions and File I/O
Programming Functions and File I/O Summary Functions Definition Declaration Invocation Pass by value vs. pass by reference File I/O Reading Writing Static keyword Global vs. local variables 2 Functions
More informationDEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS 1. Define global declaration? The variables that are used in more
More informationDay14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14
Day14 A Young W. Lim 2017-11-02 Thr Young W. Lim Day14 A 2017-11-02 Thr 1 / 14 Outline 1 Based on 2 C Strings (1) Characters and Strings Unformatted IO Young W. Lim Day14 A 2017-11-02 Thr 2 / 14 Based
More informationLecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)
Lecture 8 Data Files Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To be able to create, read, write and update
More informationProgramming & Data Structure
File Handling Programming & Data Structure CS 11002 Partha Bhowmick http://cse.iitkgp.ac.in/ pb CSE Department IIT Kharagpur Spring 2012-2013 File File Handling File R&W argc & argv (1) A file is a named
More informationCSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS
CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS A mini Quiz 2 Consider the following struct definition struct name{ int a; float b; }; Then somewhere in main() struct name *ptr,p; ptr=&p;
More informationDS: CS Computer Sc & Engg: IIT Kharagpur 1. File Access. Goutam Biswas. ect 29
DS: CS 11002 Computer Sc & Engg: IIT Kharagpur 1 File Access DS: CS 11002 Computer Sc & Engg: IIT Kharagpur 2 Standard I/O So far all our I/O operations are read from the standard input (stdin - keyboard)
More informationare all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.
CMPS 12M Introduction to Data Structures Lab Lab Assignment 3 The purpose of this lab assignment is to introduce the C programming language, including standard input-output functions, command line arguments,
More informationPreprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.
Unit-III Preprocessor: The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it
More informationUNIX Shell. The shell sits between you and the operating system, acting as a command interpreter
Shell Programming Linux Commands UNIX Shell The shell sits between you and the operating system, acting as a command interpreter The user interacts with the kernel through the shell. You can write text
More informationCSci 4061 Introduction to Operating Systems. Input/Output: High-level
CSci 4061 Introduction to Operating Systems Input/Output: High-level I/O Topics First, cover high-level I/O Next, talk about low-level device I/O I/O not part of the C language! High-level I/O Hide device
More informationChapter 10: File Input / Output
C: Chapter10 Page 1 of 6 C Tutorial.......... File input/output Chapter 10: File Input / Output OUTPUT TO A FILE Load and display the file named formout.c for your first example of writing data to a file.
More information