File Handling.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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,
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.
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
FILES Files types and operations. Files Files are used to store data Data can be Text (ASCII only: 0  127) Binary (Full range: 0  256) Each file resides.
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,
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.
20/03/01 Sudeshna Sarkar, CSE, IIT Kharagpur1 File Handling in C Lecture 17c 20/3/01.
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.
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.
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:
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.
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:
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
ME-2221 COMPUTER PROGRAMMING Lecture 18 FILE OPERATIONS Department of Mechanical Engineering A.H.M Fazle Elahi Khulna University of engineering & Technology.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
Files A collection of related data treated as a unit. Two types Text
Files Programming 1. 2 What is a File? Is a block of arbitrary information, or resource for storing information, which is available to a computer program.
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.
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.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
6/9/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 10 (C-4)
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.
TMF1414 Introduction to Programming
University of Washington Computer Programming I
Command Line Arguments
File Access (7.5) CSE 2031 Fall July 2018.
Chapter 18 I/O in C.
File I/O.
CSC215 Lecture Input and Output.
Plan for the Day: I/O (beyond scanf and printf)
Programming and Data Structures
CS111 Computer Programming
CSE1320 Files in C Dr. Sajib Datta
CSE1320 Files in C Dr. Sajib Datta
Programming in C Input / Output.
File Management in C.
Programming in C Input / Output.
Files I/O, Streams, I/O Redirection, Reading with fscanf
CSE1320 Files in C Dr. Sajib Datta
File I/O We are used to reading from and writing to the terminal:
CSE1320 Strings Dr. Sajib Datta
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
FILE HANDLING IN C.
Programming and Data Structure
File Input and Output.
Programming in C Input / Output.
C Input / Output Prabhat Kumar Padhy
Files.
File Handling in C.
Chapter 5 File Handling in C
EPSII 59:006 Spring 2004.
Module 12 Input and Output
C Programming - Lecture 3
EECE.2160 ECE Application Programming
Professor Jodi Neely-Ritz University of Florida
I/O CS580U - Fall 2018.
File I/O We are used to reading from and writing to the terminal:
Files Chapter 8.
Presentation transcript:

File Handling

Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example: Consider keeping students’ records 100 students records are added in array of structures Machine is then powered off after sometime When the machine is powered on, the 100 records entered earlier are all gone! Have to enter again if they are needed

Solution: Files A named collection of data, stored in secondary storage like disk, CD-ROM, USB drives etc. Persistent storage, not lost when machine is powered off Save data in memory to files if needed (file write) Read data from file later whenever needed (file read)

Organization of a file Stored as sequence of bytes, logically contiguous May not be physically contiguous on disk, but you do not need to worry about that The last byte of a file contains the end-of-file character (EOF), with ASCII code 1A (hex). While reading a text file, the EOF character can be checked to know the end Two kinds of files: Text : contains ASCII codes only Binary : can contain non-ASCII characters Example: Image, audio, video, executable, etc. EOF cannot be used to check end of file

Basic operations on a file Open Read Write Close Mainly we want to do read or write, but a file has to be opened before read/write, and should be closed after all read/write is over

Opening a File: fopen() FILE * is a datatype used to represent a pointer to a file fopen takes two parameters, the name of the file to open and the mode in which it is to be opened It returns the pointer to the file if the file is opened successfully, or NULL to indicate that it is unable to open the file

Example: opening file.dat for write FILE *fptr; char filename[ ]= "file2.dat"; fptr = fopen (filename,"w"); if (fptr == NULL) { printf (“ERROR IN FILE CREATION”); /* DO SOMETHING */ }

Modes for opening files The second argument of fopen is the mode in which we open the file.

Modes for opening files The second argument of fopen is the mode in which we open the file. "r" : opens a file for reading (can only read) Error if the file does not already exists "r+" : allows write also

Modes for opening files The second argument of fopen is the mode in which we open the file. "r" : opens a file for reading (can only read) Error if the file does not already exists "r+" : allows write also "w" : creates a file for writing (can only write) Will create the file if it does not exist Caution: writes over all previous contents if the flle already exists "w+" : allows read also

Modes for opening files The second argument of fopen is the mode in which we open the file. "r" : opens a file for reading (can only read) Error if the file does not already exists "r+" : allows write also "w" : creates a file for writing (can only write) Will create the file if it does not exist Caution: writes over all previous contents if the flle already exists "w+" : allows read also "a" : opens a file for appending (write at the end of the file) "a+" : allows read also

The exit() function Sometimes error checking means we want an emergency exit from a program Can be done by the exit() function The exit() function, called from anywhere in your C program, will terminate the program at once

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); } ………rest of the program………

Writing to a file: fprintf( ) fprintf() works exactly like printf(), except that its first argument is a file pointer. The remaining two arguments are the same as printf The behaviour is exactly the same, except that the writing is done on the file instead of the display FILE *fptr; fptr = fopen ("file.dat","w"); fprintf (fptr, "Hello World!\n"); fprintf (fptr, “%d %d”, a, b);

Reading from a file: fscanf( ) fscanf() works like scanf(), except that its first argument is a file pointer. The remaining two arguments are the same as scanf The behaviour is exactly the same, except The reading is done from the file instead of from the keyboard (think as if you typed the same thing in the file as you would in the keyboard for a scanf with the same arguments) The end-of-file for a text file is checked differently (check against special character EOF)

Reading from a file: fscanf( ) FILE *fptr; fptr = fopen (“input.dat”, “r”); /* Check it's open */ if (fptr == NULL) { printf(“Error in opening file \n”); exit(-1); } fscanf (fptr, “%d %d”,&x, &y); EOF checking in a loop char ch; while (fscanf(fptr, “%c”, &ch) != EOF) { /* not end of file; read */ }

Reading lines from a file: fgets() Takes three parameters a character array str, maximum number of characters to read size, and a file pointer fp Reads from the file fp into the array str until any one of these happens No. of characters read = size - 1 \n is read (the char \n is added to str) EOF is reached or an error occurs ‘\0’ added at end of str if no error Returns NULL on error or EOF, otherwise returns pointer to str

Reading lines from a file: 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); }

Writing lines to a file: fputs() Takes two parameters A string str (null terminated) and a file pointer fp Writes the string pointed to by str into the file Returns non-negative integer on success, EOF on error

Reading/Writing a character: fgetc(), fputc() Equivalent of getchar(), putchar() for reading/writing char from/to keyboard Exactly same, except that the first parameter is a file pointer Equivalent to reading/writing a byte (the char) char fgetc(FILE *fp); int fputc(char c, FILE *fp); Example: char c; c = fgetc(fp1); fputc(c, fp2);

Formatted and Un-formatted I/O Using fprintf/fscanf Can specify format strings to directly read as integers, float etc. Unformatted I/O Using fgets/fputs/fgetc/fputc No format string to read different data types Need to read as characters and convert explicitly

Closing a file Should close a file when no more read/write to a file is needed in the rest of the program File is closed using fclose() and the file pointer FILE *fptr; char filename[]= "myfile.dat"; fptr = fopen (filename,"w"); fprintf (fptr,"Hello World of filing!\n"); …. Any more read/write to myfile.dat…. fclose (fptr);

Command Line Arguments

What are they? A program can be executed by directly typing a command with parameters at the prompt $ cc –o test test.c $ ./a.out in.dat out.dat $ prog_name param_1 param_2 param_3 .. The individual items specified are separated from one another by spaces First item is the program name

What do they mean? Recall that main() is also a function It can also take parameters, just like other C function The items in the command line are passed as parameters to main Parameters argc and argv in main keeps track of the items specified in the command line

How to access them? int main (int argc, char *argv[]); Array of strings as command line arguments including the command itself. Argument Count The parameters are filled up with the command line arguments typed when the program is run They can now be accessed inside main just like any other variable

Example: Contd. $ ./a.out s.dat d.dat argc=3 ./a.out s.dat d.dat argv argv[0] = “./a.out” argv[1] = “s.dat” argv[2] = “d.dat”

Contd. Still there is a problem Solution: Use sscanf() All the arguments are passed as strings in argv[ ] But the intention may have been to pass an int/float etc. Solution: Use sscanf() Exactly same as scanf, just reads from a string (char *) instead of from the keyboard The first parameter is the string pointer, the next two parameters are exactly the same as scanf

Example Write a program that takes as command line arguments 2 integers, and prints their sum int main(int argc, char *argv[ ]) { int i, n1, n2; printf(“No. of arg is %d\n”, argc); for (i=0; i<argc; ++i) printf(“%s\n”, argv[i]); sscanf(argv[1], “%d”, &n1); sscanf(argv[2], “%d”, &n2); printf(“Sum is %d\n”, n1 + n2); return 0; } $ ./a.out 32 54 No. of arg is 3 ./a.out 32 54 Sum is 86