File Handling. 21 July 2009 Programming and Data Structure 1

Similar documents
Programming & Data Structure

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

Pointers and File Handling

Organization of a file

File IO and command line input CSE 2451

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

Standard File Pointers

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

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

C programming basics T3-1 -

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

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

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

UNIT IV-2. The I/O library functions can be classified into two broad categories:

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

Contents. A Review of C language. Visual C Visual C++ 6.0

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

25.2 Opening and Closing a File

2009 S2 COMP File Operations

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

Input/Output and the Operating Systems

Input / Output Functions

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

File I/O BJ Furman 23OCT2010

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

ENG120. Misc. Topics

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

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

PROGRAMMAZIONE I A.A. 2017/2018

C PROGRAMMING. Characters and Strings File Processing Exercise

C-Refresher: Session 10 Disk IO

CSC 270 Survey of Programming Languages. Input and Output

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

8. Characters, Strings and Files

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

Computer Programming Unit v

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

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.

CE Lecture 11

Introduction to file management

Ch 11. C File Processing (review)

Input/Output: Advanced Concepts

LANGUAGE OF THE C. C: Part 6. Listing 1 1 #include <stdio.h> 2 3 int main(int argc, char *argv[]) PROGRAMMING

File Access. FILE * fopen(const char *name, const char * mode);

C File Processing: One-Page Summary

Standard C Library Functions

Text Output and Input; Redirection

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

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

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

Engineering program development 7. Edited by Péter Vass

Review Topics. Final Exam Review Slides

File I/O. Preprocessor Macros

UNIX Shell. The shell sits between you and the operating system, acting as a command interpreter

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Chapter 11 File Processing

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof()

Chapter 12. Files (reference: Deitel s chap 11) chap8

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

Week 2 Intro to the Shell with Fork, Exec, Wait. Sarah Diesburg Operating Systems CS 3430

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

Goals of this Lecture

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

Lecture 7: file I/O, more Unix

Lecture 9: File Processing. Quazi Rahman

CSI 402 Lecture 2 Working with Files (Text and Binary)

Today s class. Review of more C Operating system overview. Informationsteknologi

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

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

File I/O Lesson Outline

C Basics And Concepts Input And Output

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

Computer programming

Recitation 2/18/2012

Computational Methods of Scientific Programming Fall 2007

Lecture 03 Bits, Bytes and Data Types

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

C Programming Language

CS240: Programming in C

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Intermediate Programming, Spring 2017*

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

Programming Fundamentals

DATA STRUCTURES USING C

Simple Output and Input. see chapter 7

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

Chapter 10: File Input / Output

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

File I/O Lesson Outline

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Transcription:

File Handling 21 July 2009 Programming and Data Structure 1

File handling in C In C we use FILE * to represent a pointer to a file. fopen is used to open a file. It returns the special value NULL to indicate that it couldn't open the file. FILE *fptr; char filename[]= "file2.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { printf ( ERROR IN FILE CREATION ); /* DO SOMETHING */ 21 July 2009 Programming and Data Structure 2

Modes for opening files The second argument of fopen is the mode in which we open the file. There are three "r" opens a file for reading "w" creates a file for writing - and writes over all previous contents (deletes the file so be careful!) "a" opens a file for appending - writing on the end of the file rb read binary file (raw bytes) wb write binary file 21 July 2009 Programming and Data Structure 3

The exit() function Sometimes error checking means we want an "emergency exit" from a program. We want it to stop dead. In main we can use "return" to stop. In functions we can use exit to do this. Exit is part of the stdlib.h library exit(-1); in a function is exactly the same as return -1; in the main routine 21 July 2009 Programming and Data Structure 4

Usage of exit( ) FILE *fptr; char filename[]= "file2.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { printf ( ERROR IN FILE CREATION ); /* Do something */ exit(-1); 21 July 2009 Programming and Data Structure 5

Writing to a file using fprintf( ) fprintf( ) works just like printf and sprintf except that its first argument is a file pointer. FILE *fptr; fptr= fopen ("file.dat","w"); /* Check it's open */ fprintf (fptr,"hello World!\n"); 21 July 2009 Programming and Data Structure 6

Reading Data Using fscanf( ) We also read data from a file using fscanf( ). FILE *fptr; fptr= fopen ( input.dat, r ); /* Check it's open */ if (fptr==null) { printf( Error in opening file \n ); fscanf(fptr, %d%d,&x,&y); input.dat 20 30 x=20 y=30 21 July 2009 Programming and Data Structure 7

Reading lines from a file using fgets( ) We can read a string using fgets ( ). FILE *fptr; char line [1000]; /* Open file and check it is open */ while (fgets(line,1000,fptr)!= NULL) { printf ("Read line %s\n",line); fgets( ) takes 3 arguments, a string, a maximum number of characters to read and a file pointer. It returns NULL if there is an error (such as EOF). 21 July 2009 Programming and Data Structure 8

Closing a file We can close a file simply using fclose( ) and the file pointer. FILE *fptr; char filename[]= "myfile.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { printf ("Cannot open file to write!\n"); exit(-1); fprintf (fptr,"hello World of filing!\n"); fclose (fptr); closing Opening Access 21 July 2009 Programming and Data Structure 9

Three special streams Three special file streams are defined in the <stdio.h> header stdin reads input from the keyboard stdout send output to the screen stderr prints errors to an error device (usually also the screen) What might this do? fprintf (stdout,"hello World!\n"); 21 July 2009 Programming and Data Structure 10

An example program Give value of i #include 15 <stdio.h> main() Value of i=15 { No error: But an example to show error message. int i; fprintf(stdout,"give value of i \n"); fscanf(stdin,"%d",&i); Display on fprintf(stdout,"value of i=%d \n",i); The screen fprintf(stderr,"no error: But an example to show error message.\n"); 21 July 2009 Programming and Data Structure 11

Input File & Output File redirection One may redirect the input and output files to other files (other than stdin and stdout). Usage: Suppose the executable file is a.out $./a.out <in.dat >out.dat No error: But an example to show error message. 15 Give value of i Value of i=15 Display screen in.dat out.dat 21 July 2009 Programming and Data Structure 12

Reading and Writing a character A character reading/writing is equivalent to reading/writing a byte. int getchar( ); int fgetc(file *fp); int putchar(int c); int fputc(int c, FILE *fp); Example: char c; c=getchar( ); putchar(c); 21 July 2009 Programming and Data Structure 13

Example: use of getchar() and putchar() #include <stdio.h> main() { int c; printf("type text and press return to see it again \n"); printf("for exiting press <CTRL D> \n"); while((c=getchar( ))!=EOF) putchar(c); End of file 21 July 2009 Programming and Data Structure 14

Command Line Arguments Command line arguments may be passed by specifying them under main( ). int main(int argc, char *argv[ ]); Argument Count Array of Strings as command line arguments including the command itself. 21 July 2009 Programming and Data Structure 15

Example: Reading command line arguments #include <stdio.h> #include <string.h> int main(int argc,char *argv[]) { FILE *ifp,*ofp; int i,c; char src_file[100],dst_file[100]; if(argc!=3){ printf("usage:./a.out <src_file> <dst_file> \n"); exit(0); else{ strcpy(src_file,argv[1]); strcpy(dst_file,argv[2]); 21 July 2009 Programming and Data Structure 16

Example: Contd. if((ifp=fopen(src_file,"r"))==null) { printf("file does not exist.\n"); exit(0); if((ofp=fopen(dst_file,"w"))==null) { printf("file not created.\n"); exit(0); while((c=getc(ifp))!=eof){ putc(c,ofp); fclose(ifp); fclose(ofp); argv./a.out s.dat d.dat argc=3./a.out s.dat d.dat 21 July 2009 Programming and Data Structure 17

Getting numbers from strings Once we've got a string with a number in it (either from a file or from the user typing) we can use atoi or atof to convert it to a number The functions are part of stdlib.h char numberstring[]= "3.14"; int i; double pi; pi= atof (numberstring); i= atoi ("12"); Both of these functions return 0 if they have a problem 21 July 2009 Programming and Data Structure 18

Example: Averaging from Command Line #include <stdio.h> #include <stdlib.h> int main(int argc,char *argv[]) { float sum=0; int i,num; $./a.out 45 239 123 Average=135.666667 num=argc-1; for(i=1;i<=num;i++) sum+=atof(argv[i]); printf("average=%f \n",sum/(float) num); 21 July 2009 Programming and Data Structure 19