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.

Slides:



Advertisements
Similar presentations
C: Advanced Topics-II Winter 2013 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
Advertisements

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.
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.
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Week 5 Part I Kyle Dewey. Overview Exam will be back Thursday New office hour More on functions File I/O Project #2.
Functions, Varargs, and Stack Smashing Using the Stack for Good And Evil Before You Sit Down Please Get The Handout at the Entrance This file is called.
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,
UNIT 15 File Processing.
Files in C Rohit Khokher.
Character String Manipulation. Overview Character string functions sscanf() function sprintf() function.
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.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Programming in C #2 Input / Output.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
File Handling Spring 2013Programming and Data Structure1.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Text and Binary File Processing 程式設計 潘仁義 CCU COMM.
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 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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.
Chapter 7 Files By C. Shing ITEC Dept Radford University.
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.
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:
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
© 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()”
CS 1704 Introduction to Data Structures and Software Engineering.
Files A collection of related data treated as a unit. Two types Text
FILES IN C. File Operations  Creation of a new file  Opening an existing file  Reading from a file  Writing to a file  Moving to a specific location.
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.
IO revisited CSE 2451 Rong Shi. stdio.h Functions – printf – scanf(normally stops at whitespace) – fgets – sscanf Standard streams – stdin(defaults to.
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.
File Access (7.5) CSE 2031 Fall July 2018.
File I/O.
CSC215 Lecture Input and Output.
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
Programming in C Input / Output.
Programming in C Input / Output.
Files I/O, Streams, I/O Redirection, Reading with fscanf
CSE1320 Files in C Dr. Sajib Datta
FILE HANDLING IN C.
Text and Binary File Processing
File Input and Output.
File Access (7.5) CSE 2031 Fall January 2019.
File Access (7.5) CSE 2031 Fall February 2019.
Programming in C Input / Output.
File Handling in C.
EPSII 59:006 Spring 2004.
Module 12 Input and Output
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Professor Jodi Neely-Ritz University of Florida
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

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 Use the file pointer and I/O functions to access the opened file Use function fclose to close the file

An Example #include main() { char ch; FILE *fp; if ((fp = fopen(“data.txt”, “r”)) == NULL) {/* 開啟檔案 */ printf(“Error: can’t open file\n”); exit(1); } while (fscanf(fp, “%c”, &ch) != EOF) /* 輸入字元 */ printf(“%c”, ch);/* 輸出字元 */ fclose(fp);/* 關閉檔案 */ }

File Pointers A file pointer points to a memory location that contains information about the file The location of a buffer The current character position in the buffer Whether the file is being read or written Whether errors or end of file have occurred

Opening a File The fopen function has the following form fp = fopen(file-name, mode) The mode may be –“r”: The file is open for reading, is used for input –“w”: The file is open for writing, is used for output, erases existing data –“a”: The file is open for appending, is used for output, keeps existing data

Closing a File The fclose function has the following form fclose(fp) You should be sure to close any files you open Exiting from a program automatically closes any open files

File I/O Input fscanf(fp, format, …) ch = getc(fp) Output fprintf(fp, format, …) putc(ch, fp)

An Example #include main() { char ch; FILE *infp, *outfp; if ((infp = fopen(“data.txt”, “r”)) == NULL) {/* 開啟輸入檔案 */ printf(“Error: can’t open input file\n”); exit(1); } if ((outfp = fopen(“result.txt”, “w”)) == NULL) {/* 開啟輸出檔案 */ printf(“Error: can’t open output file\n”); exit(1); } while (fscanf(infp, “%c”, &ch) != EOF) /* 輸入字元 */ fprintf(outfp, “%c”, ch);/* 輸出字元 */ fclose(infp); fclose(outfp);/* 關閉檔案 */ }

An Example #include main() { char ch; FILE *infp, *outfp; if ((infp = fopen(“data.txt”, “r”)) == NULL) {/* 開啟輸入檔案 */ printf(“Error: can’t open input file\n”); exit(1); } if ((outfp = fopen(“result.txt”, “a”)) == NULL) {/* 開啟增添檔案 */ printf(“Error: can’t open append file\n”); exit(1); } while (fscanf(infp, “%c”, &ch) != EOF) /* 輸入字元 */ fprintf(outfp, “%c”, ch);/* 輸出字元 */ fclose(infp); fclose(outfp);/* 關閉檔案 */ }

An Example #include main() { char ch; FILE *infp, *outfp; if ((infp = fopen(“data.txt”, “r”)) == NULL) {/* 開啟輸入檔案 */ printf(“Error: can’t open input file\n”); exit(1); } if ((outfp = fopen(“result.txt”, “w”)) == NULL) {/* 開啟輸出檔案 */ printf(“Error: can’t open output file\n”); exit(1); } while ((ch = getc(infp)) != EOF) /* 輸入字元 */ putc(ch, outfp);/* 輸出字元 */ fclose(infp); fclose(outfp);/* 關閉檔案 */ }

Standard Files The library stdio.h defines three special file pointers. These files are automatically opened at the beginning of the program and closed at the end of the program stdin: standard input file, console keyboard stdout: standard output file, console screen stderr: standard error file, console screen

Standard Files #include #include main() { char ch; while (fscanf(stdin, “%c”, &ch) != EOF) { /* 由標準輸入檔輸入字元 */ if (isupper(ch) { fprintf(stderr, “%c”, ch); /* 由標準錯誤檔輸出字元 */ } fprintf(stdout, “%c”, ch); /* 由標準輸出檔輸出字元 */ } /* fscanf(stdin, “%c”, &ch) ≡ scanf(“%c”, &ch) */ /* fprintf(stdout, “%c”, ch) ≡ printf(“%c”, ch) */ }

Redirect Standard Files Redirect an input file to standard input copyfile < infile Redirct standard output to an output file copyfile > outfile copyfile outfile Redirect standard error to an error file copyfile >& errorfile

Updating a File Open the original file for input Open a temporary file for output with a different name Copy the input file to the temporary file, updating the data in the file Close both files Delete the original file Rename the temporary file so that it once again has the original name

Updating a File Generate a new file name char *tmpnam(char s[]); tmpnam(NULL); Remove a file int remove(char *filename); Rename a file int rename(char *oldname, char *newname);

An Example #include main() { char ch, *temp; FILE *infp, *outfp; if ((infp = fopen(“data.txt”, “r”)) == NULL) { error(); } temp = tmpnam(NULL); if ((outfp = fopen(temp, “w”)) == NULL) { error(); } while ((ch = getc(infp)) != EOF) putc(toupper(ch), outfp); fclose(infp); fclose(outfp); if (remove(“data.txt”) != 0 || rename(temp, “data.txt”) != 0) { error(); }

Unget a Character The function ungetc can put a character back into input buffer int ungetc(int c, FILE *fp);

An Example void removeComments(FILE *infp, FILE *outfp) { int ch, nch; bool commentFlag; commentFlag = FALSE; while ((ch = getc(infp)) != EOF) { if (commentFlag) { if (ch = ‘*’) { nch = getc(infp); if (nch == ‘/’) { commentFlag = FALSE; } else { ungetc(nch, infp); }

An Example } else { if (ch == ‘/’) { nch = getc(infp); if (nch == ‘*’) { commentFlag = TRUE; } else { ungetc(nch, infp); } if (!commentFlag) putc(ch, outfile); }

Line I/O Input a line char *fgets(char buf[], int n, FILE *fp); fgets reads at most the next n-1 characters into the array buf, stopping if a newline is encountered; the newline is included in the array, which is terminated by ‘\0’. It returns buf or NULL if end of file or error occurs

Line I/O Output a line char *fputs(char buf[], FILE *fp); fputs writes the string buf (which need not contain ‘\n’) on fp; it returns non-negative, or EOF for an error

An Example void copyFile(FILE *infp, FILE *outfp) { char buf[MAXLINE]; while (fgets(buf, MAXLINE, infp) != NULL) { fputs(buf, outfp); }

Scanf White-space characters: any amount of white space matches any amount of white space in the input A percent sign followed by a conversion specification Any other character, which must match the next character in the input

Scanf An optional assignment-suppression flag indicated by an asterisk (*), which specifies that the value from the input should be discarded rather than stored into the argument An optional numeric field width An optional size specification (h or l)

Scanf %[…] a string consists of characters in … is read %[^…] a string consists of characters not in … is read

Sscanf and Sprintf Convert characters in an array to arguments sscanf(character-array, format, …); Convert arguments to a character array sprintf(character-array, format, …);

An Example Hydrogen, H, 1, Helium, He, 2, Lithium, Li, 3, Beryllium, Be, 4, Boron, B, 5, Carbon, C, 6, Nitrogen, N, 7, Oxygen, O, 8, Fluorine, F, 9, Neon, Ne, 10,

An Example Element (Symbol) Atomic Weight Hydrogen (H) Helium (He) Lithium (Li) Beryllium (Be) Boron (B) Carbon (C) Nitrogen (N) Oxygen (O) Fluorine (F) Neon (Ne)

An Example main() { char name[15]; char symbol[3]; char namebuf[20]; int number; double weight; char termch; int nscan; printf(" Element (symbol) Atomic Weight\n"); printf(" \n"); / * while (…) {…} */ }

An Example while (1) { nscan = scanf("%15[^,], %2[^,], %d, %lf%c", name, symbol, &number, &weight, &termch); if (nscan == EOF) break; if (nscan != 5 || termch != '\n') { fprintf(stderr, "Improper file format\n"); } sprintf(namebuf, "%s (%s)", name, symbol); printf("%3d. %-20s %8.3f\n", number, namebuf, weight); }