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,

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

File Management 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.
Using Files Declare a variable, called file pointer, of type FILE * Use function fopen to open a named file and associate this file with the file pointer.
Week 5 Part I Kyle Dewey. Overview Exam will be back Thursday New office hour More on functions File I/O Project #2.
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.
1 CSE1303 Part A Data Structures and Algorithms Semester 2, 2006 Lecture A1 – Welcome & Revision.
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.
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
1 ICS103 Programming in C Lecture 8: Data Files. 2 Outline Why data files? Declaring FILE pointer variables Opening data files for input/output Scanning.
1 CSE1301 Computer Programming: Lecture 21 File I/O.
Topic 13 – Various Other Topics. Enumerated Types.
Chapter 5: Loops and Files.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.
File Handling Spring 2013Programming and Data Structure1.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
File IO and command line input CSE 2451 Rong Shi.
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:
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.
Chapter 7 Files By C. Shing ITEC Dept Radford University.
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:
Loops and Files. 5.1 The Increment and Decrement Operators.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Files A collection of related data treated as a unit. Two types Text
CSC Programming for Science Lecture 18: More Data Files.
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
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.
1 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
Chapter 7 Text Input/Output Objectives
File Access (7.5) CSE 2031 Fall July 2018.
File I/O.
Plan for the Day: I/O (beyond scanf and printf)
CS111 Computer Programming
File Input/Output.
Computer Programming Lecture 15 Text File I/O
Programming in C Input / Output.
Programming in C Input / Output.
Files I/O, Streams, I/O Redirection, Reading with fscanf
File I/O We are used to reading from and writing to the terminal:
Lesson #5 Repetition and Loops.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Programming and Data Structure
File Input and Output.
File Handling.
File Access (7.5) CSE 2031 Fall January 2019.
File Access (7.5) CSE 2031 Fall February 2019.
Programming in C Input / Output.
Files.
File Handling in C.
Module 12 Input and Output
CS1100 Computational Engineering
C Programming - Lecture 3
CSc 352 File I/O Saumya Debray Dept. of Computer Science
I/O CS580U - Fall 2018.
Professor Jodi Neely-Ritz University of Florida
File I/O We are used to reading from and writing to the terminal:
Files Chapter 8.
Presentation transcript:

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, use printf().

To get input from a file (instead of the keyboard) we can use input redirection: % a.out < inputfile Use the same scanf() calls we use to read from the keyboard. The operating system causes input to come from the file instead of the keyboard.

% a.out > outputfile Use printf() as before Output of the program goes to a file instead of the screen.

Both types of redirection can be used at the same time... % a.out outputfile

While redirection is very useful, it is really part of the operating system (not C). C has own mechanism for reading and writing files, which is more flexible than redirection alone.

There are types and functions in the library stdio.h that are used for file I/O. Make sure you always include that header when you use files. #include

For files you want to read or write, you need a file pointer, e.g.: FILE *fp; What is this type "FILE *"?  abstract data structure  the only way you can use a FILE * is via the functions that C gives you. Note: In reality, FILE is some kind of structure that holds information about the file. We must use a FILE * because certain functions will need to change that information (pass by reference).

Reading from or writing to a file in C requires 3 basic steps: 1. Open the file. 2. Do all the reading or writing. 3. Close the file.

To open a file, use fopen() : fp = fopen(filename, mode); where: filename is a string that holds the name of the file on disk (including a path like /home/penguin/ if necessary). mode is a string representing how you want to open the file. Most often you'll open a file for reading ( "r" ) or writing ( "w" ). fopen() returns a FILE * that can then be used to access the file. When the file cannot be opened (e.g., we don't have permission or it doesn't exist when opening for reading), fopen() will return NULL.

FILE *ifp, *ofp; char *mode = "r"; char outputFilename[] = "out.list"; ifp = fopen("in.list", mode); if (ifp == NULL) { fprintf(stderr, "Can't open input file in.list!\n"); exit(1); } ofp = fopen(outputFilename, "w"); if (ofp == NULL) { fprintf(stderr, "Can't open output file %s!\n", outputFilename); exit(1); }

The input file that we are opening for reading ( "r" ) must already exist. The output file we are opening for writing ( "w" ) does not have to exist.  If it doesn't, it will be created.  If it does, its previous contents will be overwritten. Note: There are other modes you can use when opening a file

r - open for reading w - open for writing (file need not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists)

Once a file has been opened:  read from it using fscanf()  write to it using fprintf() These functions work just like scanf() and printf(), except they require an extra first parameter, a FILE *. Note: There are other functions in stdio.h that can be used to read or write files.

Continuing our example from above, suppose the input file consists of lines with a username and an integer test score, e.g.: in.list foo 70 bar and that each username is no more than 8 characters long.

Format SpecifierType %d (or %i)int %cchar %fFloat %lfdouble %sistring %xhexadecimal

char username[9]; /* One extra for null char. */ int score;... while (fscanf(ifp, "%s %d", username, &score) != EOF) { fprintf(ofp, "%s %d\n", username, score+10); }...

The function fscanf(), like scanf(), normally returns the number of values it was able to read in. When it hits the end of the file, it returns the special value EOF. Testing the return value against EOF is one way to stop the loop.

The bad thing about testing against EOF is that if the file is not in the right format (e.g., a letter is found when a number is expected): in.list foo 70 bar 98 biz A+... then fscanf() will not be able to read that line (since there is no integer to read) and it won't advance to the next line in the file. For this error, fscanf() will not return EOF (it's not at the end of the file).... Errors like that will at least mess up how the rest of the file is read. In some cases, they will cause an infinite loop.

One solution is to test against the number of values we expect to be read by fscanf() each time. while (fscanf(ifp, "%s %d", username, &score) == 2) {... Now, if we get 2 values, the loop continues. If we don't get 2 values, either we are at the end of the file or some other problem occurred, then the loop will end.

When done with a file, it must be closed using the function fclose(). To finish our example, we'd want to close our input and output files: fclose(ifp); fclose(ofp); Closing a file is very important, especially with output files. The reason is that output is often buffered. This means that when you tell C to write something out, e.g., fprintf(ofp, "Whatever!\n"); it doesn't necessary get written to disk right away, but may end up in a buffer in memory.

Sample output buffer: | a | b | c | W | h | a | t | e | v | e | r | | ! | \n | | | | | | | | | | | | | | | | | | | | | | (The buffer is really just 1-dimensional.) When the buffer fills up (or when the file is closed), the data is finally written to disk. So, if you forget to close an output file then whatever is still in the buffer may not be written out.

There are 3 special FILE *'s that are always defined:  stdin (standard input)  stdout (standard output)  stderr (standard error).

Standard Input Standard input is where things come from when you use scanf(). In other words, scanf("%d", &val); is equivalent to: fscanf(stdin, "%d", &val);

Standard Output Standard output is where things go when you use printf(). In other words, printf("Value = %d\n", val): is equivalent to: fprintf(stdout, "Value = %d\n", val): Remember that standard input is normally associated with the keyboard and standard output with the screen, unless redirection is used.

Standard Error Standard error is where you should display error messages. We've already done that above: fprintf(stderr, "Can't open input file in.list!\n"); Standard error is normally associated with the same place as standard output; however, redirecting standard output does not redirect standard error. For example, % a.out > outfile only redirects stuff going to standard output to the file outfile... anything written to standard error goes to the screen.

We've already seen that stderr is useful for printing error messages, but you may be asking, "When would I ever use the special file pointers stdin and stdout?" Well, suppose you create a function that writes a bunch of data to an opened file that is specified as a parameter: void WriteData(FILE *fp) { fprintf(fp, "data1\n"); fprintf(fp, "data2\n");... }

Certainly, you can use it to write the data to an output file (like the one above): WriteData(ofp); But, you can also write the data to standard output: WriteData(stdout); Without the special file pointer stdout, you'd have to write a second version of WriteData() that wrote stuff to standard output. Writing to stdout is also helpful when debugging.

 write a friends.dat file and then read it in and print contents