BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

Size: px
Start display at page:

Download "BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12"

Transcription

1 BIL 104E Introduction to Scientific and Engineering Computing Lecture 12

2 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 a concrete device with which you want to exchange information. Before you perform any communication to a file, you have to open the file. Then you need to close the opened file after you finish exchanging information with it. The data flow you transfer from your program to a file, or vice versa, is called a stream, which is a series of bytes. Not like a file, a stream is device-independent. All streams have the same behavior. To perform I/O operations, you can read from or write to any type of files by simply associating a stream to the file. There are two formats of streams. The first one is called the text stream, which consists of a sequence of characters (that is, ASCII data). Depending on the compilers, each character line in a text stream may be terminated by a newline character. Text streams are used for textual data, which has a consistent appearance from one environment to another, or from one machine to another. The second format of streams is called the binary stream, which is a series of bytes. The content of an.exe file would be one example. Binary streams are primarily used for nontextual data, which is required to keep the exact contents of the file. 10/4/11 Lecture 12 2

3 I/O Statements Each file used in a program must have a file pointer associated with it. A file pointer is defined with a FILE declaration. FILE data type is defined in the header file stdio.h. After a file pointer is defined, it must be associated with a specific file. The fopen function obtains the information needed to assign a file pointer to a specific file. The two arguments for this function are the file name and a character that indicates the file status, which is also called the file open mode. If we are going to read information from a file with a program, the file open mode is r for read. If we are going to write information to a file with a program, the file open mode is w for write. The fclose function is used to close a file after we are finished with it. The function argument is the file pointer. 10/4/11 Lecture 12 3

4 File Opening Modes "r" opens an existing text file for reading. "w" creates a text file for writing. "a" opens an existing text file for appending. "r+" opens an existing text file for reading or writing. "w+" creates a text file for reading or writing. "a+" opens or creates a text file for appending. "rb" opens an existing binary file for reading. "wb" creates a binary file for writing. "ab" opens an existing binary file for appending. "r+b" opens an existing binary file for reading or writing. "w+b" creates a binary file for reading or writing. "a+b" opens or creates a binary file for appending. Note that you might see people use the mode "rb+" instead of "r+b". These two strings are equivalent. Similarly, "wb+" is the same as "w+b"; "ab+" is equivalent to "a+b". 10/4/11 Lecture 12 4

5 /* Opening and closing a file */ #include <stdio.h> enum {SUCCESS, FAIL; main(void) { FILE *fptr; char filename[]= "haiku.txt"; int reval = SUCCESS; if ((fptr = fopen(filename, "r")) == NULL){ printf("cannot open %s.\n", filename); reval = FAIL; else { printf("the value of fptr: 0x%p\n", fptr); printf("ready to close the file."); fclose(fptr); return reval; 10/4/11 Lecture 12 5

6 fgetc and fputc functions The fgetc and fputc functions are used to read/write one character at a time. The int fgetc(file *stream) function fetches the next character from the stream specified by stream. The function then returns the value of an int that is converted from the character. The int fputc(int c, FILE *stream) function prints the character that corresponds to the integer argument to the specified file stream. It then returns the same character as the function value if it is successful; otherwise, it returns EOF. After a character is written, fputc() advances the associated file pointer. 10/4/11 Lecture 12 6

7 /* Reading and writing one character at a time */ #include <stdio.h> enum {SUCCESS, FAIL; void CharReadWrite(FILE *fin, FILE *fout); main(void) { FILE *fptr1, *fptr2; char filename1[]= "outhaiku.txt"; char filename2[]= "haiku.txt"; int reval = SUCCESS; if ((fptr1 = fopen(filename1, "w")) == NULL) { printf("cannot open %s.\n", filename1); reval = FAIL; else if ((fptr2 = fopen(filename2, "r")) == NULL) { printf("cannot open %s.\n", filename2); reval = FAIL; else { CharReadWrite(fptr2, fptr1); fclose(fptr1); fclose(fptr2); return reval; void CharReadWrite(FILE *fin, FILE *fout) { int c; while ((c=fgetc(fin))!= EOF){ /* write to a file */ fputc(c, fout); /* put the character */ /*on the screen */ putchar(c); 10/4/11 Lecture 12 7

8 fgets Function The fgets function is used to read one line of text at a time. The char *fgets (char *s, int n, FILE *stream) function: Here s references a character array that is used to store characters read from the opened file pointed to by the file pointer stream. n specifies the maximum number of array elements. If it is successful, it returns the char pointer s. If an error occurs, the function returns a null pointer, and the contents of the array are unknown. The fgets() function can read up to n-1 characters, and can append a null character after the last character fetched, until a newline or an EOF is encountered. If a newline is encountered during the reading, the fgets() function includes the newline in the array. Note, this is different from what gets() function does. The gets() function just replaces the newline character with a null character. If EOF is encountered, the fgets() function returns a null pointer and leaves the array untouched. 10/4/11 Lecture 12 8

9 fputs Function The fputs function is used to write one line of text at a time. The int fputs (const char *s, FILE *stream) function: Here s points to the array that contains the characters to be written to a file associated with the file pointer stream. The const modifier indicates that the content of the array pointed to by s cannot be changed. If it fails, the fputs() function returns a nonzero value; otherwise, it returns zero. Note that the character array must include a null character at the end as the terminator to the fputs() function. Also, unlike the puts() function, the fputs() function does not insert a newline character to the string written to a file. 10/4/11 Lecture 12 9

10 /* Reading and writing one line of text at a time */ #include <stdio.h> enum {SUCCESS, FAIL, MAX_LEN = 81; void LineReadWrite (FILE *fin, FILE *fout); main(void) { FILE *fptr1, *fptr2; char filename1[]= "outhaiku.txt"; char filename2[]= "haiku.txt"; int reval = SUCCESS; if ((fptr1 = fopen (filename1, "w")) == NULL){ printf ("Cannot open %s for writing.\n", filename1); reval = FAIL; else if ((fptr2 = fopen (filename2, "r")) == NULL){ printf ("Cannot open %s for reading.\n", filename2); reval = FAIL; else { LineReadWrite(fptr2, fptr1); fclose (fptr1); fclose (fptr2); return reval; void LineReadWrite(FILE *fin, FILE *fout) { char buff[max_len]; while (fgets (buff, MAX_LEN, fin)!= NULL){ fputs (buff, fout); printf ("%s", buff); 10/4/11 Lecture 12 10

11 fread Function The fread function is used to read one block of characters at a time. The size_t fread (void *ptr, size_t size, size_t n, FILE *stream) function: Here ptr is a pointer to an array in which the data is stored. size indicates the size of each array element. n specifies the number of elements to read. stream is a file pointer that is associated with the opened file for reading. size_t is an integral type defined in the header file stdio.h. The fread() function returns the number of elements actually read. The number of elements read by the fread() function should be equal to the value specified by the third argument to the function, unless an error occurs or an EOF (end-of-file) is encountered. The fread() function returns the number of elements that are actually read, if an error occurs or an EOF is encountered. 10/4/11 Lecture 12 11

12 fwrite Function The fwrite function is used to write one block of characters at a time. The size_t fwrite (const void *ptr, size_t size, size_t n, FILE *stream) function: Here ptr references the array that contains the data to be written to an opened file pointed to by the file pointer stream. size indicates the size of each element in the array. n specifies the number of elements to be written. The fwrite() function returns the number of elements actually written. If there is no error occurring, the number returned by fwrite() should be the same as the third argument in the function. The return value may be less than the specified value if an error occurs. Note that it's the programmer's responsibility to ensure that the array is large enough to hold data for either the fread() function or the fwrite() function. 10/4/11 Lecture 12 12

13 feof Function The feof function can be used to determine when the end of a file is encountered. The int feof (FILE *stream) function Here stream is the file pointer that is associated with an opened file. The feof() function returns 0 if the end of the file has not been reached; otherwise, it returns a nonzero integer. This function is more useful when a binary file is read because the values of some bytes may be equal to the value of EOF. If the end of a binary file is determined by checking the value returned by fread(), we may end up at the wrong position. Using the feof() function helps us to avoid mistakes in determining the end of a file. 10/4/11 Lecture 12 13

14 /*Reading and writing one block at a time */ #include <stdio.h> enum {SUCCESS, FAIL, MAX_LEN = 80; void BlockReadWrite(FILE *fin, FILE *fout); int ErrorMsg(char *str); main(void) { FILE *fptr1, *fptr2; char filename1[]= "outhaiku.txt"; char filename2[]= "haiku.txt"; int reval = SUCCESS; if ((fptr1 = fopen(filename1, "w")) == NULL){ reval = ErrorMsg(filename1); else if ((fptr2 = fopen(filename2, "r")) == NULL){ reval = ErrorMsg(filename2); else { BlockReadWrite(fptr2, fptr1); return reval; fclose(fptr1); fclose(fptr2); void BlockReadWrite(FILE *fin, FILE *fout) { int num; char buff[max_len + 1]; while (!feof(fin)){ num = fread(buff, sizeof(char), MAX_LEN, fin); /* append a null character */ buff[num * sizeof(char)] = '\0'; printf("%s", buff); fwrite(buff, sizeof(char), num, fout); int ErrorMsg(char *str) { printf("cannot open %s.\n", str); return FAIL; 10/4/11 Lecture 12 14

15 fscanf function Once an input file and its pointer have been specified, information can be read from it by using the fscanf function. fscanf statement converts the characters from the lines in the data file to values. Example: Each line in the sensor1.dat file contains a time and sensor reading: #include <stdio.h> FILE *sensor1; sensor1 = fopen("sensor1.dat","r"); fscanf(sensor1, "%lf %lf", &time, &motion); fclose(sensor1); 10/4/11 Lecture 12 15

16 fprintf function If the file is an output file, we can write information to the file with the fprintf function. Example: #include <stdio.h> FILE *balloon; balloon = fopen("balloon.dat", "w"); fprintf (balloon, "%f %f %f\n", time, height, velocity/3600); fclose(balloon); 10/4/11 Lecture 12 16

17 /* This program generates a summary report from a data file */ /* that has the number of data points in the first record. */ #include <stdio.h> #incude <stdlib.h> #define FILENAME "sensor1.dat" main(){ int num_data_pts, k; double time, motion, sum=0, maximum, minimum; FILE *sensor1; sensor1 = fopen (FILENAME, "r"); fscanf (sensor1, "%i", &num_data_pts); for (k=1; k<=num_data_pts; k++);{ fscanf (sensor1, "%lf %lf", &time, &motion); if (k == 1) maximum = minimum = motion; sum += motion; if (motion > maximum) maximum = motion; if (motion < minimum) minimum = motion; printf ("Number of sensor readings: %i \n", num_data_pts); printf ("Average reading : %.2f \n", sum/num_data_pts); printf ("Maximum reading : %.2f \n", maximum); printf ("Minimum reading : %.2f \n", minimum); fclose (sensor1); return EXIT_SUCCESS; /4/11 Lecture 12 17

18 /* This program generates a summary report from a data file */ /* that has a trailer record with negative values*/ #include <stdio.h> #incude <stdlib.h> #define FILENAME "sensor2.dat" main(){ int num_data_pts=0, k; double time, motion, sum=0, maximum, minimum; FILE *sensor2; sensor2 = fopen (FILENAME, "r"); fscanf (sensor2, "%lf %lf", &time, &motion); maximum = minimum = motion; do{ sum += motion; if (motion > maximum) maximum = motion; if (motion < minimum) minimum = motion; num_data_pts++; fscanf(sensor2, "%lf %lf", &time, &motion); while (time >= 0); printf ("Number of sensor readings : %i \n", num_data_pts); printf ("Average reading : %.2f \n", sum/num_data_pts); printf ("Maximum reading : %.2f \n", maximum); printf ("Minimum reading : %.2f \n", minimum); fclose (sensor2); return EXIT_SUCCESS; /4/11 Lecture 12 18

19 /* This program generates a summary report from a data file */ /* that does not have a header record or a trailer record */ #include <stdio.h> #incude <stdlib.h> #define FILENAME "sensor3.dat" main(){ int num_data_pts=0, k; double time, motion, sum=0, maximum, minimum; FILE *sensor3; sensor3 = fopen (FILENAME, "r"); while (( fscanf (sensor3, "%lf %lf", &time, &motion)) ==2){ num_data_pts++; if (num_data_pts ==1) maximum = minimum = motion; sum += motion; if (motion > maximum) maximum = motion; if (motion < minimum) minimum = motion; printf ("Number of sensor readings : %i \n", num_data_pts); printf ("Average reading : %.2f \n", sum/num_data_pts); printf ("Maximum reading : %.2f \n", maximum); printf ("Minimum reading : %.2f \n", minimum); fclose (sensor3); return EXIT_SUCCESS; 10/4/11 Lecture 12 19

Introduction to file management

Introduction 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 information

fopen() fclose() fgetc() fputc() fread() fwrite()

fopen() 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 information

File IO and command line input CSE 2451

File 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 information

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

Content. 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 information

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

CMPE-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 information

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

C 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 information

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Files 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 information

UNIT IV-2. The I/O library functions can be classified into two broad categories:

UNIT 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 information

M.CS201 Programming language

M.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 information

Organization of a file

Organization 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 information

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Mode 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 information

CS240: Programming in C

CS240: 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 information

System Software Experiment 1 Lecture 7

System 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 information

Lecture 9: File Processing. Quazi Rahman

Lecture 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 information

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Quick 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 information

File I/O. Arash Rafiey. November 7, 2017

File 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 information

Standard C Library Functions

Standard 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 information

Input/Output and the Operating Systems

Input/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 information

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Fundamentals 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 information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Darshan 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 information

File (1A) Young Won Lim 11/25/16

File (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 information

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

Preprocessing 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 information

Standard File Pointers

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 information

Programming & Data Structure

Programming & 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 information

C Basics And Concepts Input And Output

C 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 information

Lecture 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 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 information

C 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; 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 information

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.

Files. 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 information

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

Systems 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 information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE 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 information

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

Day14 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 information

CSI 402 Lecture 2 Working with Files (Text and Binary)

CSI 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 information

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan File Processing Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline 11.2 The Data Hierarchy 11.3 Files and Streams 11.4 Creating a Sequential

More information

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSC209H Lecture 3. Dan Zingaro. January 21, 2015 CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

CSCI 171 Chapter Outlines

CSCI 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 information

25.2 Opening and Closing a File

25.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 information

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

Unit 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 information

C programming basics T3-1 -

C 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 information

Ch 11. C File Processing (review)

Ch 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 information

Fundamentals of Programming & Procedural Programming

Fundamentals 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 information

Pointers and File Handling

Pointers 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 information

Engineering program development 7. Edited by Péter Vass

Engineering 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 information

Chapter 12. Files (reference: Deitel s chap 11) chap8

Chapter 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 information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C 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 information

File Handling. 21 July 2009 Programming and Data Structure 1

File 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 information

File I/O. Preprocessor Macros

File 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 information

C-Refresher: Session 10 Disk IO

C-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 information

Computer System and programming in C

Computer System and programming in C File Handling in C What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary storage so that the contents of files remain intact

More information

Input / Output Functions

Input / 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 information

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Lecture 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 information

ENG120. Misc. Topics

ENG120. 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 information

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

CS246 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 information

Chapter 11 File Processing

Chapter 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 information

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

CMPT 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 information

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

Day14 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 information

System Programming. Standard Input/Output Library (Cont d)

System Programming. Standard Input/Output Library (Cont d) Content : by Dr. B. Boufama School of Computer Science University of Windsor Instructor: Dr. A. Habed adlane@cs.uwindsor.ca http://cs.uwindsor.ca/ adlane/60-256 Content Content 1 Binary I/O 2 3 4 5 Binary

More information

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

7/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 information

CS240: Programming in C

CS240: Programming in C CS240: Programming in C Lecture 15: Unix interface: low-level interface Cristina Nita-Rotaru Lecture 15/Fall 2013 1 Streams Recap Higher-level interface, layered on top of the primitive file descriptor

More information

C File Processing: One-Page Summary

C 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 information

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

UNIT-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 information

Solutions to Chapter 7

Solutions to Chapter 7 Solutions to Chapter 7 Review Questions 1. a. True 3. b. False 5. a. True 7. c. stdfile 9. a. Opens the file for reading and sets the file marker at the beginning. 11. a. Conversion code 13. a. scanf implicitly

More information

EM108 Software Development for Engineers

EM108 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 information

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100 FINAL EXAMINATION INTRODUCTION TO ALGORITHMS AND PROGRAMMING II 03-60-141-01 U N I V E R S I T Y O F W I N D S O R S C H O O L O F C O M P U T E R S C I E N C E Winter 2014 Last Name: First Name: Student

More information

C mini reference. 5 Binary numbers 12

C 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 information

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS113: 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 information

Accessing 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 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 information

Computer programming

Computer 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 information

Data File and File Handling

Data 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 information

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment. Lecture 12 CSE 110 20 July 1992 Today we ll cover the things that you still don t know that you need to know in order to do the assignment. 1 The NULL Pointer For each pointer type, there is one special

More information

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

CSci 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 information

CE Lecture 11

CE 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 information

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Copyright 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 information

Naked C Lecture 6. File Operations and System Calls

Naked C Lecture 6. File Operations and System Calls Naked C Lecture 6 File Operations and System Calls 20 August 2012 Libc and Linking Libc is the standard C library Provides most of the basic functionality that we've been using String functions, fork,

More information

Procedural Programming

Procedural Programming Exercise 5 (SS 2016) 28.06.2016 What will I learn in the 5. exercise Strings (and a little bit about pointer) String functions in strings.h Files Exercise(s) 1 Home exercise 4 (3 points) Write a program

More information

Lecture6 File Processing

Lecture6 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 information

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who

More information

Computer Programming Unit v

Computer 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 information

UNIX System Programming

UNIX System Programming File I/O 경희대학교컴퓨터공학과 조진성 UNIX System Programming File in UNIX n Unified interface for all I/Os in UNIX ü Regular(normal) files in file system ü Special files for devices terminal, keyboard, mouse, tape,

More information

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof()

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof() Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who

More information

A stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions

A stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions Topic: File input/output I. Streams II. Access methods III. C++ style Input, output, random access Stream classes: ifstream, ofstream IV. C style The FILE data type Opening files Writing to, reading text

More information

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

Programming 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 information

Lab # 4. Files & Queues in C

Lab # 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 information

Fundamentals of Programming. Lecture 15: C File Processing

Fundamentals 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 information

UNIX Shell. The shell sits between you and the operating system, acting as a command interpreter

UNIX 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 information

Slide Set 8. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Slide Set 8. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng Slide Set 8 for ENCM 339 Fall 2017 Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary October 2017 ENCM 339 Fall 2017 Section 01 Slide

More information

Input/Output: Advanced Concepts

Input/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 information

SAE1A Programming in C. Unit : I - V

SAE1A 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 information

ECE264 Spring 2014 Exam 2, March 11, 2014

ECE264 Spring 2014 Exam 2, March 11, 2014 ECE264 Spring 2014 Exam 2, March 11, 2014 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing it.

More information

Programming. Functions and File I/O

Programming. 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 information

C Programming Language

C 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 information

C: How to Program. Week /June/18

C: How to Program. Week /June/18 C: How to Program Week 17 2007/June/18 1 Chapter 11 File Processing Outline 11.1 Introduction 11.2 The Data Hierarchy 11.3 Files and Streams 11.4 Creating a Sequential Access File 11.5 Reading Data from

More information

Week 9 Lecture 3. Binary Files. Week 9

Week 9 Lecture 3. Binary Files. Week 9 Lecture 3 Binary Files 1 Reading and Writing Binary Files 2 Binary Files It is possible to write the contents of memory directly to a file. The bits need to be interpreted on input Possible to write out

More information

CS1003: Intro to CS, Summer 2008

CS1003: 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 information

Text Output and Input; Redirection

Text Output and Input; Redirection Text Output and Input; Redirection see K&R, chapter 7 Simple Output puts(), putc(), printf() 1 Simple Output The simplest form of output is ASCII text. ASCII occurs as single characters, and as nullterminated

More information

Standard I/O in C, Computer System and programming in C

Standard I/O in C, Computer System and programming in C Standard I/O in C, Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files and Information 7. Environment

More information

CS 261 Fall Mike Lam, Professor. Structs and I/O

CS 261 Fall Mike Lam, Professor. Structs and I/O CS 261 Fall 2018 Mike Lam, Professor Structs and I/O Typedefs A typedef is a way to create a new type name Basically a synonym for another type Useful for shortening long types or providing more meaningful

More information

Data Files. Computer Basics

Data Files. Computer Basics Unit 10 Data Files Computer Basics Contents What is a data file? Basic operations with data files: Opening a data file Closing a data file Types of data files Text Files Reading text files Writing text

More information

Programming Fundamentals

Programming Fundamentals Programming Fundamentals Day 4 1 Session Plan Searching & Sorting Sorting Selection Sort Insertion Sort Bubble Sort Searching Linear Search Binary Search File Handling Functions Copyright 2004, 2 2 Sorting

More information

SAMPLE MIDTERM SOLUTION

SAMPLE MIDTERM SOLUTION CMPT 102 SAMPLE MIDTERM SOLUTION PART 1 (40 points): SHORT ANSWER QUESTIONS 1. (8 points) Which of the following identifiers are invalid? Why? int my_book while loop FOR butter iff sentinel Calc-mean MeanOf45

More information