1 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering

Slides:



Advertisements
Similar presentations
I/O means Input and Output. One way: use standard input and standard output. To read in data, use scanf() (or a few other functions) To write out data,
Advertisements

UNIT 15 File Processing.
BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
File Management in C. A file is a collection of related data that a computers treats as a single unit. File is a collection of data stored permanently.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
CSCI 171 Presentation 12 Files. Working with files File Streams – sequence of data that is connected with a specific file –Text Stream – Made up of lines.
1 Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A1 – Welcome & Revision.
1 CSE1301 Computer Programming: Lecture 21 File I/O.
Topic 13 – Various Other Topics. Enumerated Types.
1 CSE1301 Computer Programming: Lecture 9 Input/Output.
CSE1301 Computer Programming: Lecture 19 File I/O
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
1 CSE1301 Computer Programming: Lecture 19 File I/O.
Chapter 18 I/O in C.
Programming Languages -1 (Introduction to C) files Instructor: M.Fatih AMASYALI
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
File IO and command line input CSE 2451 Rong Shi.
CSE1301 Computer Programming: Lecture 14 I/O and Files.
ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
1 Data Structures and Algorithms Programs. Different problems. Operations. Size of data. Resources available.
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Kymberly Fergusson WELCOME CSE1303 Part A Data Structures and Algorithms Summer 2002.
Lecture 8a: File I/O BJ Furman 21MAR2011. Learning Objectives Explain what is meant by a data stream Explain the concept of a ‘file’ Open and close files.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
CNG 140 C Programming (Lecture set 10) Spring Chapter 10 Data Files.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
CSE1301 Computer Programming: Lecture 6 Input/Output.
CS 261 – Recitation 7 Spring 2015 Oregon State University School of Electrical Engineering and Computer Science.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
Files A collection of related data treated as a unit. Two types Text
CSCI N305: C Programming Copyright ©2006  Department of Computer & Information Science File Handling in C.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic properties and characteristics of external files ❏ To.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
Chapter 18 I/O in C Original slides from Gregory Byrd, North Carolina State University Modified slides by C. Wilcox, Y. Malaiya Colorado State University.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
Introduction to Computing Lecture 03: Basic input / output operations Introduction to Computing Lecture 03: Basic input / output operations Assist.Prof.Dr.
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
File Access (7.5) CSE 2031 Fall July 2018.
Chapter 18 I/O in C.
Introduction to Computer Programming Lecture 18 Binary Files
File I/O.
CS 261 – Recitation 7 Fall 2013 Oregon State University
Plan for the Day: I/O (beyond scanf and printf)
CSE1320 Files in C Dr. Sajib Datta
File Input/Output.
CSE1320 Files in C Dr. Sajib Datta
Computer Programming Lecture 15 Text File I/O
Programming in C Input / Output.
Programming in C Input / Output.
CSE1320 Files in C Dr. Sajib Datta
CSI 121 Structured Programming Language Lecture 7: Input/Output
Chapter 18 I/O in C.
File Input and Output.
File Handling.
Chapter 18 I/O in C.
Programming in C Input / Output.
Module 12 Input and Output
Chapter 11 Files chap8.
I/O CS580U - Fall 2018.
Files Chapter 8.
Chapter 18 I/O in C.
Presentation transcript:

1 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering

2 Topics Sequential File Handling in C Basic File I/O Functions Example: Count words in a file

3 Introduction C can process two kinds of files –Text and binary All the files created using an editor or word processor are text files A text file is a named collection of characters

4 Text Files A text file has no fixed size To mark the end of a text file, a special end-of-file character is placed at the end of each file Also at the end of each line, there is a newline character (‘\n’ in C) E.g. –This is a text file! It has two lines. These characters are not visible!

5 File Handling in C Files need to be opened before use. –Associate a "file handler" to each file –Modes: read, write, or append File input/output functions use the file handler (not the filename) Need to close the file after use. Basic file handling functions: fopen(), fclose(), fscanf(), fprintf()

6 File I/O Example Write a program which: –inputs a list of names from a file called names.lst –counts the number of names in the list –asks a mark for each name in the file –outputs the name and corresponding mark to the file names_marks.dat Note: the tasks above are not necessarily accomplished in that order

7 File I/O (Header) Step 0: Include stdio.h. #include int main() {... return 0; }

8 File I/O (File Pointer) Step 1: Declare a file handler (a.k.a. file pointer) as FILE * for each file. int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; FILE *currentfile = NULL;... return 0; }

9 File I/O (Open) Step 2: Open file using fopen(). int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; FILE *currentfile = NULL; inputfile = fopen(“Names.txt”, “r”); outputfile = fopen(“marks.dat”, “w”); currentfile = fopen(“logFile.txt”, “a”);... return 0; }

10 File I/O (Open) Step 2: Open file using fopen(). int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; FILE *currentfile = NULL; inputfile = fopen(“Names.txt”, “r”); outputfile = fopen(“marks.dat”, “w”); currentfile = fopen(“logFile.txt”, “a”);... return 0; } File name

11 File I/O (Open) Step 2: Open file using fopen(). int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; FILE *currentfile = NULL; inputfile = fopen(“Names.txt”, “r”); outputfile = fopen(“marks.dat”, “w”); currentfile = fopen(“logFile.txt”, “a”);... return 0; } Mode r : read w : write a : append Warning: The "w" mode overwrites the file, if it exists.

12 File I/O (Open) Step 2: Open file using fopen(). int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; FILE *currentfile = NULL; inputfile = fopen(“Names.txt”, “r”); outputfile = fopen(“marks.dat”, “w”); currentfile = fopen(“logFile.txt”, “a”);... return 0; } Other Modes r+ : both reading and writing. (The file must exist) w+ : both reading and writing. (If the given file exists, its contents are destroyed) a+ : reading and appending

13 File I/O (Open) Step 2: Open file using fopen(). int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; FILE *currentfile = NULL; inputfile = fopen(“Names.txt”, “r”); outputfile = fopen(“marks.dat”, “w”); currentfile = fopen(“logFile.txt”, “a”);... return 0; } Associate a file handler for every file to be used.

14 File I/O (Error Check) Step 3: Check if file is opened successfully. int main() { FILE *inputfile; inputfile = fopen(“Names.txt”, “r”); if (inputfile == NULL) { printf(“Unable to open input file.\n”); return 1; }... return 0; }

15 File I/O (Error Check) Step 3: Check if file is opened successfully. int main() { FILE *inputfile; inputfile = fopen(“Names.txt”, “r”); if (inputfile == NULL) { printf(“Unable to open input file.\n”); return 1; }... return 0; } File handler becomes NULL when an fopen() error occurs.

16 File I/O (Error Check) Step 3: Check if file is opened successfully. int main() { FILE *inputfile; inputfile = fopen(“Names.txt”, “r”); if (inputfile == NULL) { printf(“Unable to open input file.\n”); return 1; }... return 0; } Ends program if inside main ( ) function.

17 File I/O (Input) Step 4a: Use fscanf() for input. #include #define MAXLEN 100 int main() { FILE *inputfile = NULL; char name[MAXLEN]; int count; listnames.c

18 File I/O (Input) Step 4a: Use fscanf() for input. #include #define MAXLEN 100 int main() { FILE *inputfile = NULL; char name[MAXLEN]; int count; Recall: Macro definition

19 File I/O (Input) Step 4a: Use fscanf() for input. /* Assuming "names.lst" contains a list of names, open this file for reading. */ inputfile = fopen("names.lst", "r"); if (inputfile == NULL) { printf("Error opening names file.\n"); return 1; } listnames.c

20 File I/O (Input) Step 4a: Use fscanf() for input. /* Read in each name, and keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name) == 1 ) { count++; printf("%d. %s\n", count, name); } printf("\nNumber of names read: %d\n", count); return 0; } listnames.c

21 File I/O (Input) Step 4a: Use fscanf() for input. /* Read in each name, and keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name) == 1 ) { count++; printf("%d. %s\n", count, name); } printf("\nNumber of names read: %d\n", count); return 0; } listnames.c Requires the file handler (“stream”), not the file name.

22 File I/O (Input) Step 4a: Use fscanf() for input. /* Read in each name, and keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name) == 1 ) { count++; printf("%d. %s\n", count, name); } printf("\nNumber of names read: %d\n", count); return 0; } Other parameters: like ordinary scanf(). listnames.c

23 File I/O (Input) Step 4a: Use fscanf() for input. /* Read in each name, and keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name) == 1 ) { count++; printf("%d. %s\n", count, name); } printf("\nNumber of names read: %d\n", count); return 0; } fscanf() returns the number of input items converted and assigned successfully. listnames.c

24 /* Read in each name, and keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name) == 1 ) { count++; printf("%d. %s\n", count, name); } printf("\nNumber of names read: %d\n", count); return 0; } File I/O (Input) Step 4a: Use fscanf() for input. Used to check if a read or assignment error occured, or end of input file has been reached. listnames.c

25 File I/O (Output) Step 4b: Use fprintf() for output. #include #define MAXLEN 100 int main() { FILE *inputfile = NULL; FILE *outfile = NULL; char name[MAXLEN]; int count; float mark; /* Assuming "names.lst" contains a list of names, open this file for reading. */ inputfile = fopen("names.lst", "r"); if (inputfile == NULL) { printf("Error opening names file.\n"); return 1; } listnames2.c

26 File I/O (Output) Step 4b: Use fprintf() for output. /* The output file "names_marks.dat" will contain the list of names and corresponding marks. */ outfile = fopen("names_marks.dat", "w"); if (outfile == NULL) { printf("Error opening output file.\n"); return 1; } listnames2.c

27 File I/O (Output) Step 4b: Use fprintf() for output. /* Read in each name, ask for the mark, and write name and mark to output file. Also keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name ) == 1 ) { count++; printf("Enter mark for %s: ", name); scanf("%f", &mark); if ( fprintf(outfile, "%s %f\n", name, mark) <= 0 ) { printf("Error writing to output file.\n"); return 1; } /*** etc ***/ listnames2.c

28 File I/O (Output) Step 4b: Use fprintf() for output. /* Read in each name, ask for the mark, and write name and mark to output file. Also keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name ) == 1 ) { count++; printf("Enter mark for %s: ", name); scanf("%f", &mark); if ( fprintf(outfile, "%s %f\n", name, mark) <= 0 ) { printf("Error writing to output file.\n"); return 1; } /*** etc ***/ File handler, not the file name. listnames2.c

29 File I/O (Output) Step 4b: Use fprintf() for output. /* Read in each name, ask for the mark, and write name and mark to output file. Also keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name ) == 1 ) { count++; printf("Enter mark for %s: ", name); scanf("%f", &mark); if ( fprintf(outfile, "%s %f\n", name, mark) <= 0 ) { printf("Error writing to output file.\n"); return 1; } /*** etc ***/ Other parameters: like ordinary printf(). listnames2.c

30 /* Read in each name, ask for the mark, and write name and mark to output file. Also keep count how many names there are in the file. */ count = 0; while ( fscanf(inputfile, "%s", name ) == 1 ) { count++; printf("Enter mark for %s: ", name); scanf("%f", &mark); if ( fprintf(outfile, "%s %f\n", name, mark) <= 0 ) { printf("Error writing to output file.\n"); return 1; } /*** etc ***/ File I/O (Output) Step 4b: Use fprintf() for output. fprintf() returns the number of characters written out successfully, or negative if an error occurs. listnames2.c

31 File I/O (Close) Step 5: Close file using fclose() int main() { /*** etc ***/ printf("\n"); printf("Number of names read: %d\n", count); fclose(inputfile); fclose(outfile); return 0; }

32 File I/O (Close) Step 5: Close file using fclose() int main() { /*** etc ***/ printf("\n"); printf("Number of names read: %d\n", count); fclose(inputfile); fclose(outfile); return 0; } File handler, not the file name.

33 File I/O (Close) Step 5: Close file using fclose() int main() { /*** etc ***/ printf("\n"); printf("Number of names read: %d\n", count); fclose(inputfile); fclose(outfile); return 0; } Clears input buffer. Flushes output buffer. fclose() fails when the file was not opened successfully.

34 Notes on Filenames Unless a directory path is specified, the program will look for the file in the current directory Directory paths in filenames: DOS/Windows sysFile = fopen(“C:\\win\\system.ini”, “r”); Directory paths in filenames: Unix passFile = fopen(“/usr/etc/passwd”, “r”);

35 Notes on Filenames Variable filenames: FILE *outFile = NULL; char someName[MAX_NAME_LEN]; printf(“Please enter output filename: ”); scanf(“%s”, someName); outFile = fopen(someName, “w”);

36 File I/O and Streams Recall: A stream serves as a channel to convey characters between I/O devices and programs Standard streams: stdin, stdout, stderr A file handler/pointer serves as a stream to/from a file Once an item is read from an input stream, the file position moves automatically, and the next item (if any) becomes available for the next read ("sequential access")

37 Notes on Strings and fscanf() Reading in a string: fscanf( stream, “%s”, string ) –Reads only a "word" at a time. –Words are separated by a white-space: (space, tab, newline, or any combination of these) –Moves to the next word in the stream automatically after each read. scanf(“%s”, string ) –behaves similarly, except input stream is stdin.

38 Checking for EOF count = 0; while ( fscanf(inputfile, "%s", name) != EOF ) { count++; printf("%d. %s\n", count, name); } Both scanf() and fscanf() return: –the number of input items converted and assigned successfully –or the constant value EOF when an error or end-of-file occurs, but... Not recommended!

39 Checking for EOF Can cause bad problems if the conversion specifiers do not match the file's contents. Warning! Use EOF with caution! while ( fscanf( inpf, "%s %f", name, &mark) != EOF ) { printf("%s\t %f\n", name, mark); } listmarks.c inpf: Jake absent Example:

40 Checking for EOF To check for end-of-file (or any other input error), check that the number of items converted and assigned successfully is equal to the expected number of items while ( fscanf( inpf, "%s %f", name, &mark) == 2 ) { printf("%s\t %f\n", name, mark); } listmarks.c

41 if ( scanf( "%d %d %d", &page, &row, &col) != 3 ) { printf( "I cannot go on without 3 integers :-( \n" ); exit(1); } Checking for EOF Ditto for scanf(). testscanf1.c To check for end-of-file (or any other input error), check that the number of items converted and assigned successfully is equal to the expected number of items.

42 To check for end-of-file (or any other input error), check that the number of items converted and assigned successfully is equal to the expected number of items. if ( scanf( "%d %d %d", &page, &row, &col) != 3 ) { printf( "I cannot go on without 3 integers :-( \n" ); exit(1); } Checking for EOF The exit() function causes the program to terminate immediately; Requires #include

43 Summary Sequential File handling EOF/Error Checking Additions to your "C vocabulary": –FILE * –fopen(), fscanf(), fprint(), fclose() –exit()