Ch 6-2. File Input / Output

Similar documents
EP241 Computing Programming

Ch 6-1. Structures. March 30, Prof. Young-Tak Kim

System Software Experiment 1 Lecture 7

Ch 6-8. C-Strings. April 30, Prof. Young-Tak Kim

Simple File I/O.

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

What we will learn about this week:

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

Programming Language B

Introduction to file management

Ch 6. Structures and Classes

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

File I/O CS 16: Solving Problems with Computers I Lecture #9

Standard File Pointers

C++ Input/Output: Streams

Chapter 12. Streams and File I/O

C Programming 1. File Access. Goutam Biswas. Lect 29

Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance

Example. Section: PS 709 Examples of Calculations of Reduced Hours of Work Last Revised: February 2017 Last Reviewed: February 2017 Next Review:

2009 S2 COMP File Operations

Today s Learning Objectives

File I/O BJ Furman 23OCT2010

Standard C Library Functions

COMP322 - Introduction to C++

M.CS201 Programming language

Object Oriented Programming In C++

File I/O Christian Schumacher, Info1 D-MAVT 2013

CS349/SE382 A1 C Programming Tutorial

DS: CS Computer Sc & Engg: IIT Kharagpur 1. File Access. Goutam Biswas. ect 29

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Programming in C/C

C Structures & Dynamic Memory Management

typedef int Array[10]; String name; Array ages;

File IO and command line input CSE 2451

Computer Programming Unit v

Note: The buy help from the TA for points will apply on this exam as well, so please read that carefully.

Scientific Computing

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

EM108 Software Development for Engineers

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

C Basics And Concepts Input And Output

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

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

Objects and streams and files CS427: Elements of Software Engineering

Do not turn to the next page until the start of the exam.

Ch 4. Parameters and Function Overloading

ENCM 335 Fall 2018 Lab 6 for the Week of October 22 Complete Instructions

SAE1A Programming in C. Unit : I - V

Intermediate Programming, Spring 2017*

PROGRAMMAZIONE I A.A. 2017/2018

Input / Output Functions

Goals of this Lecture

High Performance Programming Programming in C part 1

C mini reference. 5 Binary numbers 12

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

I/O Management! Goals of this Lecture!

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

I/O Management! Goals of this Lecture!

Ch 5-2. Arrays Part 2

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

Formatting functions in C Language

Data Types and Variables in C language

Input/Output: Advanced Concepts

Classes and Objects. Instructor: 小黑

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

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

OBJECT ORIENTED PROGRAMMING USING C++

Ch 1. Algorithms and Basic C++ Programming

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

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

WARM UP LESSONS BARE BASICS

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Computer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010

Arrays, Strings, & Pointers

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

Input and Output File (Files and Stream )

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

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

Programming in C/C

Week 5: Files and Streams

Computer Programming: Skills & Concepts (CP) Files in C

UNIX input and output

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

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

We will exclusively use streams for input and output of data. Intro Programming in C++

Basic and Practice in Programming Lab 10

CSE 12 Spring 2016 Week One, Lecture Two

1 Pointer Concepts. 1.1 Pointer Examples

Chapter 8 File Processing

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

C Programming Language

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

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

Unit-V File operations

Transcription:

2014-1 Ch 6-2. File Input / Output March 30, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497; Fax : +82-53-810-4742 http://antl.yu.ac.kr/; E-mail : ytkim@yu.ac.kr)

Outline File Output fprintf() File Input fscanf() File Input/Output with iostream ch 6-2 - 2

File open File open (1) prepare data reading and writing from/to file after file open, data reading and writing are possible sequence of file handling: File open File read & write File close access file through FILE structure file pointer (FILE *fp) points FILE structure for each file, individual file pointer is necessary FILE *fopen (const char *name, const char *mode); name : string of file name mode : file access mode ch 6-2 - 3

File open (2) File mode mode r w a r+ w+ a+ b Open file as read mode description Open file as write mode. If file is not existing, the file is created. If file is existing, that file is erased. Open file as append mode. File a file with the same name is existing, data are appended at the end of the existing file. If file is not existing, a new file is created. Open file as read mode and write mode. File should be existing. Open file as read mode and write mode. If file is not existing, a new file is created. If file is existing, new data are overwritten on the existing file. Open file as read and append mode. File a file with the same name is existing, data are appended at the end of the existing file. File reading can be at any position. If file is not existing, a new file is created. File is opened as binary file mode. ch 6-2 - 4

File close fclose() close opened file defined in <stdio.h> if file is successfully closed, return 0 if file closing fails, return -1 int fclose (FILE *stream) ch 6-2 - 5

Create Sample.txt File open/close Project -> sample.txt creation Example of file open/close #include "stdio.h" int main() { FILE *fp = NULL; //create FILE pointer fp, and initialize to be NULL fp = fopen("sample.txt", "w"); // open file in write mode, and store that address in fp if (fp == NULL) printf( Failed to open file!! n"); else printf( Successful file open!! n"); fclose(fp); //close file } return 0; ch 6-2 - 6

Text File Write (2) Formatted input / output integer or float data are converted into string, and stored into file fprintf() usage is similar to printf(), but output into file instead of console int fprintf( FILE *fp, const char *format, ); example of usage of fprintf() #include <stdio.h> int main() { int i = 23; float f = 1.2345; FILE *fp = NULL; // create FILE pointer fp, and initialize to be NULL fp = fopen("sample.txt", "w"); // open file in write mode, and store that address in fp if(fp!= NULL) fprintf(fp, "%10d %16.4f", i, f); fclose(fp); //close file return 0; } ch 6-2 - 7

Example Formatted file output in C - fprintf() fprintf(fp, Color %s, Number %d, Float %5.2f, red, 123456, 3.14); Output: Color red, Number 123456, Float 3.14 int x = 7; double d = 12.5; fprintf(fp, %4d, x); // prints out integer x in 4 places fprintf(fp, "%2d", 3); // prints out " 3 fprintf(fp, "%02d", 3); // prints out "03". fprintf(fp, %4d, %4x, 15, 15); // prints out 15, F fprintf(fp, %7.2f, d); // printout double d in total 7 places // with 2 digits to the right of decimal points ch 6-2 - 8

Format specifier in printf() Format Character Output data type Output %d int signed decimal integer %u unsigned int unsigned decimal integer %o unsigned int unsigned octal integer %x, %X unsigned int unsigned hexadecimal integer %f float, double floating point numbers in decimal format %e, %E float, double floating point numbers in scientific format (e.g., 1.2345e-001 or 1.0E-20) %g, %G float, double selects %f or %e according to the value %c char character %s char * string indicated by a character pointer %p void * address value of the pointer %n int * address value of the pointer ch 6-2 - 9

Additional format specifier printf("%d, %o, %x n", data, data,data); // decimal, octal, hexa-decimal printf("%4d, %4o, %4x n", data, data,data); // %4d : print in 4 spaces, right-alignment printf("%#d, %#o, %#X n", data, data,data); // # defines prefix of 0 for octal number, // 0xF for hexa-decimal number printf("%#08d, %#08o, %#08X n", data, data, data); // #0 defines filling leading zeros ( 0 ) in front of the number printf("%8d, %-8d, %+8d n", data, data, data); // by default numbers are printed in right-alignment // - defines left-alignment in printing numbers ch 6-2 - 10

Text File Read (3) fscanf() similar to scanf(), but input from file, instead of console (keyboard) int fscanf( FILE *fp, const char *format, ); example usage of fscanf() #include <stdio.h> int main() { int i; float f; FILE *fp = NULL; //create FILE pointer fp, and initialize to be NULL fp = fopen("sample.txt", "r"); // open file in read mode, and store that address in fp if(fp!= NULL) fscanf(fp, "%d %f", &i, &f); // formatted input from file printf(" %d\n %f\n", i, f); //print on console screen fclose(fp); // close file } return 0; ch 6-2 - 11

Example Formatted input in C scanf() char mystr[20]; int int_d; double dble_d; code: scanf( %s %d %f, mystr, &int_d, &dbl_d); input: SampleString 1234 3.14159 ch 6-2 - 12

Format specifier in scanf() Format Character Output data type Output %d int signed decimal integer %i int signed decimal integer %u unsigned int unsigned decimal integer %o unsigned int unsigned octal integer %x unsigned int unsigned hexadecimal integer %c char character %s char * string indicated by a character pointer %p void * address value of the pointer %f, %e, %g float signed floating point number ch 6-2 - 13

Example of File Input / Output /** FileInputOutput.cpp */ #include <stdio.h> #include <string.h> #define MAX_WORD_LEN 50 #define NUM_WORDS 100 int main() { FILE *pfin = NULL; FILE *pfout = NULL; char str[80]; char wordlist[num_words][max_word_len]; int word_count; pfin = fopen("input.txt", "r"); if (pfin == NULL) { printf("error in input data file open!! n"); return 0; } ch 6-2 - 14

/** FileInputOutput.cpp (2) */ pfout = fopen("output.txt", "w"); if (pfout == NULL) { printf("error in output data file creation!! n"); return 0; } word_count = 0; while (fscanf(pfin, "%s", str)!= EOF) { printf("%2d-th input word: %s n", word_count, str); strcpy(wordlist[word_count], str); word_count++;; } printf("number of words: %d n", word_count); for (int i=0; i<word_count; i++) { fprintf(pfout, "wordlist[%2d]: %s (length: %d) n", i, wordlist[i], strlen(wordlist[i])); } fprintf(pfout, " n"); fclose(pfin); fclose(pfout); } ch 6-2- 15

input.txt one two three four five six seven eight nine ten January February March April May June July August September October Sunday Monday Tuesday Wednesday Thursday Friday Saturday week day month China India UnitedStates Indonesia Brazil Pakistan Nigeria Russia Bangladesh Japan Mexico Philippines Vietnam Ethiopia Germany Egypt Iran Turkey Congo Thailand France UnitedKingdom Italy ch 6-2 - 16

output.txt wordlist[ 0]: one (length: 3) wordlist[ 1]: two (length: 3) wordlist[ 2]: three (length: 5) wordlist[ 3]: four (length: 4) wordlist[ 4]: five (length: 4) wordlist[ 5]: six (length: 3) wordlist[ 6]: seven (length: 5) wordlist[ 7]: eight (length: 5) wordlist[ 8]: nine (length: 4) wordlist[ 9]: ten (length: 3) wordlist[10]: January (length: 7) wordlist[11]: February (length: 8) wordlist[12]: March (length: 5) wordlist[13]: April (length: 5) wordlist[14]: May (length: 3) wordlist[15]: June (length: 4) wordlist[16]: July (length: 4) wordlist[17]: August (length: 6) wordlist[18]: September (length: 9) wordlist[19]: October (length: 7) wordlist[20]: Sunday (length: 6) wordlist[21]: Monday (length: 6) wordlist[22]: Tuesday (length: 7) wordlist[23]: Wednesday (length: 9) wordlist[24]: Thursday (length: 8) wordlist[25]: Friday (length: 6) wordlist[26]: Saturday (length: 8) wordlist[27]: week (length: 4) wordlist[28]: day (length: 3) wordlist[29]: month (length: 5) wordlist[30]: China (length: 5) wordlist[31]: India (length: 5) wordlist[32]: UnitedStates (length: 12) wordlist[33]: Indonesia (length: 9) wordlist[34]: Brazil (length: 6) wordlist[35]: Pakistan (length: 8) wordlist[36]: Nigeria (length: 7) wordlist[37]: Russia (length: 6) wordlist[38]: Bangladesh (length: 10) wordlist[39]: Japan (length: 5) wordlist[40]: Mexico (length: 6) wordlist[41]: Philippines (length: 11) wordlist[42]: Vietnam (length: 7) wordlist[43]: Ethiopia (length: 8) wordlist[44]: Germany (length: 7) wordlist[45]: Egypt (length: 5) wordlist[46]: Iran (length: 4) wordlist[47]: Turkey (length: 6) wordlist[48]: Congo (length: 5) wordlist[49]: Thailand (length: 8) wordlist[50]: France (length: 6) wordlist[51]: UnitedKingdom (length: 13) wordlist[52]: Italy (length: 5) ch 6-2 - 17

File Input / Output using fstream We ve used streams already cin Input stream object connected to keyboard cout Output stream object connected to screen Can define other streams To or from files Used similarly as cin, cout ch 6-2 - 18

file stream Must first connect file to stream object For input: File ifstream object For output: File ofstream object Classes ifstream and ofstream Defined in library <fstream> Named in std namespace Usage: #include <fstream> using namespace std; ch 6-2 - 19

Example of file stream input & output header file /** * ChemElmnt.h */ ChemicalElm.txt 1 Hydrogen H 1 1 2 Helium He 18 1 3 Lithium Li 1 2 typedef struct ChemicalElement { int automicno; char name[36]; char chsymbol[4]; int group; int period; } ChemElmnt; ch 6-2 - 20

including header file and Data File ch 6-2 - 21

/** ChemElmnt.cpp */ #include <iostream> #include <fstream> // for file input, output #include "ChemElmnt.h" using namespace std; void main() { ifstream instream; ofstream outstream; char name[32], symbol[6]; int automicno, group, period, count; instream.open("chemicalelm.txt"); if (instream.fail()) { cout << "Input file opening failed. n"; return; } outstream.open("output.txt"); if (outstream.fail()) { cout << "Output file opening failed. n"; return; } ch 6-2 - 22

count = 0; while (!instream.eof()) { instream >> automicno; instream >> name; instream >> symbol; instream >> group; instream >> period; cout <<"AutomicNo (" << automicno << "), name: " << name ; cout << ", symbol: " << symbol << ", group: " << group; cout << ", period: " << period << endl; outstream <<"AutomicNo (" << automicno << "), name: " << name; outstream << ", symbol: " << symbol << ", group: " << group; outstream << ", period: " << period << endl; count++; } instream.close(); outstream.close(); } cout << endl << endl; ch 6-2 - 23

Console output File output: Output.txt AutomicNo (1), name: Hydrogen, symbol: H, group: 1, period: 1 AutomicNo (2), name: Helium, symbol: He, group: 18, period: 1 AutomicNo (3), name: Lithium, symbol: Li, group: 1, period: 2 ch 6-2 - 24

Homework 6-2 6-2.1 Structure for Chemical Elements 1) Design and write a struct for chemical elements, struct ChElmnt, that contains following attributes: int automicno; // 1 ~ 120; non-duplicated char name[32]; // name of the chemical element (e.g., Hydrogen, Helium, Oxygen, Carbon, Neon, Iron, ) char chsymbol[4]; // chemical Symbol, (e.g., H, He, O, C, Ne, Ir,... ) int group; // 1 ~ 18 int period; // 1 ~ 7 2) Design and write a function, void initelmnts(), that prepares 20 struct array of chemical elements. The initelmnts() function reads in the input data file ChemicalElements.dat and initialize each elements. 3) Design and write a function, void printelmnts(chelmnt list[], int num), that prints out the attributes (automicno, name, chemical symbol, group, period ) of each chemical element in the list of structure. ch 6-2 - 25

4) Design and write a function, void searchelmntbychno (ChElmnt list[], int num, int atno), that searches the array of chemical elements with the given automic number (atno), and prints out the attributes of the chemical element. 5) Design and write a function, void sortelmntsbychno(), that sorts the array of chemical elements according to automic number, in increasing order. 6) Design and write a function, void sortelmntsbyname(), that sorts the array of chemical elements according to name, in increasing order. 7) Design and write a main() function, that includes the headfile ChemicalElement.h, invokes functions in following sequence: - initelemnt() - printelemnt() - sortelmntsbyname() - printelemnt() - sortelmntsbychno() - printelemnt() The main() function receives user s input of automicno, and search the array of chemical elements for the specified element using searchelmntbychno(), and printout the attributes of the element. ch 6-2 - 26

ChemicalElements.dat No Name Symbol Group Period 1 Hydrogen H 1 1 2 Helium He 18 1 3 Lithium Li 1 2 4 Beryllium Be 2 2 5 Boron B 13 2 6 Carbon C 14 2 7 Nitrogen N 15 2 8 Oxygen O 16 2 9 Fluorine F 17 2 10 Neon Ne 18 2 11 Sodium Na 1 3 12 Magnesium Mg 2 3 13 Aluminium Al 13 3 14 Silicon Si 14 3 15 Phosphorus P 15 3 16 Sulfur S 16 3 17 Chlorine Cl 17 3 18 Argon Ar 18 3 19 Potassium K 1 4 20 Calcium Ca 2 4 ch 6-2 - 27