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