File Handling. What is a file?



Similar documents
As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Module 816. File Management in C. M. Campbell 1993 Deakin University

System Calls and Standard I/O

Tutorial on C Language Programming

Lecture 16: System-Level I/O

The C Programming Language course syllabus associate level

So far we have considered only numeric processing, i.e. processing of numeric data represented

Illustration 1: Diagram of program function and data flow

Informatica e Sistemi in Tempo Reale

Embedded Systems Design Course Applying the mbed microcontroller

C Examples! Jennifer Rexford!

/* File: blkcopy.c. size_t n

5 Arrays and Pointers

Operating Systems. Privileged Instructions

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

DESIGN: A Program to Create Data Entry Programs

Lecture 25 Systems Programming Process Control

Member Functions of the istream Class

arrays C Programming Language - Arrays

Fundamentals of Programming

Simple C Programs. Goals for this Lecture. Help you learn about:

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

SQLITE C/C++ TUTORIAL

Sources: On the Web: Slides will be available on:

Lex et Yacc, exemples introductifs

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Basics of I/O Streams and File I/O

LOW LEVEL FILE PROCESSING

Lexical Analysis and Scanning. Honors Compilers Feb 5 th 2001 Robert Dewar

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Linux/UNIX System Programming. POSIX Shared Memory. Michael Kerrisk, man7.org c February 2015

The programming language C. sws1 1

LEX/Flex Scanner Generator

Giving credit where credit is due

How To Write Portable Programs In C

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Project 2: Bejeweled

Channel Access Client Programming. Andrew Johnson Computer Scientist, AES-SSG

List of FTP commands for the Microsoft command-line FTP client

Simple Image File Formats

System Calls Related to File Manipulation

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Lab 4: Socket Programming: netcat part

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Perl version documentation - Digest::SHA NAME SYNOPSIS SYNOPSIS (HMAC-SHA) Page 1

Character Translation Methods

PHP Debugging. Draft: March 19, Christopher Vickery

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Advanced Bash Scripting. Joshua Malone

CSCE 665: Lab Basics. Virtual Machine. Guofei Gu

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT COURSE CURRICULUM. Course Title: Advanced Computer Programming (Code: )

How to Write a Simple Makefile

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Foundations of Programming Using C

Comparing RTOS to Infinite Loop Designs

Introduction to Programming II Winter, 2014 Assignment 2

public static void main(string[] args) { System.out.println("hello, world"); } }

Counting in base 10, 2 and 16

2- Electronic Mail (SMTP), File Transfer (FTP), & Remote Logging (TELNET)

IPC. Semaphores were chosen for synchronisation (out of several options).

URI and UUID. Identifying things on the Web.

Command Scripts Running scripts: include and commands

10CS35: Data Structures Using C

Stack Overflows. Mitchell Adair

A real-time satellite system based on UNIX

C++ Input/Output: Streams

Storing Measurement Data

Shared Memory Segments and POSIX Semaphores 1

Interface and Simulation of a LCD Text Display

V850E2/ML4 APPLICATION NOTE. Performance Evaluation Software. Abstract. Products. R01AN1228EJ0100 Rev Aug. 24, 2012

Module 16: Some Other Tools in UNIX

Buffer Overflows. Code Security: Buffer Overflows. Buffer Overflows are everywhere. 13 Buffer Overflow 12 Nov 2015

UNIX, Shell Scripting and Perl Introduction

Simple File Input & Output

Chapter 7 Assembly Language

An Incomplete C++ Primer. University of Wyoming MA 5310

DToolsX-DWG. Version: An ActiveX DLL To Retrieve DWG/DXF information. DToolsX-DWG REFERENCE MANUAL

Number Representation

Network Working Group. October 1990

D06 PROGRAMMING with JAVA

CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17

PROBLEMS (Cap. 4 - Istruzioni macchina)

PYTHON Basics

Version 4 MAT-File Format

An Implementation of a Tool to Detect Vulnerabilities in Coding C and C++

C PROGRAMMING FOR MATHEMATICAL COMPUTING

CP Lab 2: Writing programs for simple arithmetic problems

Record Storage and Primary File Organization

Software Vulnerabilities

Programming the PIC18/ XC8 Using C- Coding Dr. Farahmand

Operating Systems and Programming Languages

Transcription:

File Handling 1 What is a file? A named collection of data, stored in secondary storage (typically). Typical operations on files: Open Read Write Close How is a file stored? Stored as sequence of bytes, logically contiguous (may not be physically contiguous on disk). 2 1

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 Image, audio, video, executable, etc. To check the end of file here, the file size value (also stored on disk) needs to be checked. 3 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 is unable to open the file. FILE *fptr; char filename[]= "file2.dat"; fptr = fopen (filename,"w"); if (fptr == NULL) { printf ( ERROR IN FILE CREATION ); /* DO SOMETHING */ 4 2

Modes for opening files The second argument of fopen is the mode in which we open the file. There are three modes. "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. 5 We can add a b character to indicate that the file is a binary file. rb, wb or ab fptr = fopen ( xyz.jpg, rb ); 6 3

The exit() function Sometimes error checking means we want an "emergency exit" from a program. 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 7 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); 8 4

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"); fprintf (fptr, %d %d, a, b); 9 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); 10 5

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, maximum number of characters to read, and a file pointer. It returns NULL if there is an error (such as EOF). 11 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); 12 6

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"); 13 #include <stdio.h> main() { int i; An example program fprintf(stdout,"give value of i \n"); fscanf(stdin,"%d",&i); fprintf(stdout,"value of i=%d \n",i); fprintf(stderr,"no error: But an example to show error message.\n"); Give value of i 15 Value of i=15 No error: But an example to show error message. 14 7

Input File & Output File redirection One may redirect the standard input and standard output to other files (other than stdin and stdout). Usage: Suppose the executable file is a.out: $./a.out <in.dat >out.dat scanf() will read data inputs from the file in.dat, and printf() will output results on the file out.dat. 15 A Variation $./a.out <in.dat >>out.dat scanf() will read data inputs from the file in.dat, and printf() will append results at the end of the file out.dat. 16 8

Reading and Writing a character A character reading/writing is equivalent to reading/writing a byte. int getchar( ); stdin, stdout int putchar(int c); int fgetc(file *fp); int fputc(int c, FILE *fp); file Example: char c; c = getchar(); putchar(c); 17 Example: use of getchar() & 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); 18 9

Command Line Arguments 19 What are they? A program can be executed by directly typing a command at the operating system 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. Variables argc and argv keep track of the items specified in the command line. 20 10

How to access them? 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 Example: Contd. $./a.out s.dat d.dat argc=3 argv./a.out s.dat d.dat argv[0] =./a.out argv[1] = s.dat argv[2] = d.dat 22 11

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]); 23 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 = fgetc(ifp))!= EOF) { fputc (c,ofp); fclose(ifp); fclose(ofp); 24 12

Example: with command-line arguments Write a program which will take the number of data items, followed by the actual data items on the command line, and print the average. $./a.out 6 10 17 35 12 28 33 No. of data items argv[1] = 10 argv[2] = 17, and so on 25 Getting numbers from strings Once we have 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. 26 13

Alternatively, we can use sscanf(). For example, if argv[1]= 10 and argv[2]= 17, then we can read their values into integer variables as: sscanf (argv[1], %d, &n1); sscanf (argv[2], %d, &n2); 27 Reading one line at a time It is quite common to want to read every line in a program. The best way to do this is a while loop using fgets(). FILE *fptr; char tline[100]; fptr = fopen ("sillyfile.txt", "r"); /* check it's open */ while (fgets (tline, 100, fptr)!= NULL) { printf ("%s", tline); // Print it fclose (fptr); 28 14