Computer System and programming in C

Similar documents
Darshan Institute of Engineering & Technology for Diploma Studies Unit 6


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

CSI 402 Lecture 2 (More on Files) 2 1 / 20

File (1A) Young Won Lim 11/25/16

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

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

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

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

File Handling. Reference:

C Programming Language

System Software Experiment 1 Lecture 7

EM108 Software Development for Engineers

Intermediate Programming, Spring 2017*

PROGRAMMAZIONE I A.A. 2017/2018

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

SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY, VIRUDHUNAGAR Department of CSE & IT Internal Test I

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

fopen() fclose() fgetc() fputc() fread() fwrite()

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

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

Introduction to file management

CS240: Programming in C

Input / Output Functions

Chapter 12. Text and Binary File Processing. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

Input/Output and the Operating Systems

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

C-Refresher: Session 10 Disk IO

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

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

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

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

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

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

Computer Programming Unit v

CSE2301. Introduction. Streams and Files. File Access Random Numbers Testing and Debugging. In this part, we introduce

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Standard C Library Functions

25.2 Opening and Closing a File

ENG120. Misc. Topics

Computer programming

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Lecture 9: File Processing. Quazi Rahman

Introduction to Computer and Program Design. Lesson 6. File I/O. James C.C. Cheng Department of Computer Science National Chiao Tung University

UNIX System Programming

Standard File Pointers

File I/O. Preprocessor Macros

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

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

M.CS201 Programming language

2009 S2 COMP File Operations

Data File and File Handling

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

a = ^ ^ ^ ^ ^ ^ ^ b = c = a^b =

Input/Output: Advanced Concepts

C File Processing: One-Page Summary

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

Week 9 Lecture 3. Binary Files. Week 9

Ch 11. C File Processing (review)

Library Functions. General Questions

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

Naked C Lecture 6. File Operations and System Calls

A stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Introduction to Computer Programming Lecture 18 Binary Files

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

mywbut.com 12 File Input/Output

Fundamental File Processing Operations 2. Fundamental File Processing Operations

Chapter 10. File Processing 248 FILE PROCESSING

UNIX input and output

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

UNIT- 2. Binary File

C Basics And Concepts Input And Output

System Programming. Standard Input/Output Library (Cont d)

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

CE Lecture 11

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

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

Goals of this Lecture

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

Chapter 11 File Processing

I/O Management! Goals of this Lecture!

I/O Management! Goals of this Lecture!

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

Lecture6 File Processing

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

CSE2301. Introduction

Engineering program development 7. Edited by Péter Vass

CAAM 420 Notes Chapter 2: The C Programming Language

Lecture 8: Structs & File I/O

HIGH LEVEL FILE PROCESSING

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 Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

File I/O BJ Furman 23OCT2010

C PROGRAMMING. Characters and Strings File Processing Exercise

(3-3) File Processing with Functions. Instructor - Andrew S. O Fallon CptS 121 (January 26, 2018) Washington State University

Organization of a file

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

LAB 13 FILE PROCESSING

CS1003: Intro to CS, Summer 2008

Transcription:

File Handling 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 storage so that the contents of files remain intact when a computer turns off. When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device. C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.

Steps in Processing a File 1. Create the stream via a pointer variable using the FILE structure: FILE *p; 2. Open the file, associating the stream name with the file name. 3. Read or write the data. 4. Close the file.

The basic file operations are fopen - open a file- specify how its opened (read/write) and type (binary/text) fclose - close an opened file fread - read from a file fwrite - write to a file fseek/fsetpos - move a file pointer to somewhere in a file. ftell/fgetpos - tell you where the file pointer is located.

File Open Modes

More on File Open Modes

Additionally, r+ (read + write) In this mode we can also write and modify existing data.the file to be opened must exist and the previous data of file is not erased. This mode is also called update mode. w+ (write + read) If the file doesn t exist then a new file is created and if the file exists than the previous data is erased. a+ (append + read) In this mode we can append as well as read the existing file.

File Open The file open function (fopen) serves two purposes: It makes the connection between the physical file and the stream. It creates a program file structure to store the information. Syntax: FILE*fopen( filename, mode );

More On fopen On success fopen() returns a pointer of type FILE and on error it returns NULL. We assign the return value of fopen to our pointer variable: FILE *p1; p1= fopen( MYFILE.TXT, w ); p1= fopen( A: ( A:\\DOCUMENTS\\MYFILE.TXT, MYFILE.TXT, w );

Errors in fopen If an error occurs in opening a file,then fopen() returns NULL. FILE *p; p=fopen( abc.txt, r ); if(p==null) { printf( Error in opening file ); exit(1); }

Errors may occur due to following reasons If we try to open a file in read mode and If the file doesn t exists or we do not have read permission on that file. If we try to create a file but there is no space on disk or we don t have write permissions. If we try to create a file that already exists and we don t have permission to delete that file. Operating system limits the number of files that can be opened at a time and we are trying to open more files than that number.

Closing a File When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file. To close a file, we use fclose and the pointer variable: fclose(p1);

fprintf() Syntax: fprintf (fp,"string",variables); Example: int i = 12; float x = 2.356; char ch = 's'; FILE *fp; fp=fopen( out.txt, w ); fprintf (fp, "%d %f %c", i, x, ch);

fscanf() Syntax: Example: fscanf (fp,"string",identifiers); FILE *fp; Fp=fopen( input.txt, r ); int i; fscanf (fp, %d",i);

getc() Syntax: identifier = getc (file pointer); Example: FILE *fp; fp=fopen( input.txt, r ); char ch; ch = getc (fp);

putc() write a single character to the output file, pointed to by fp. Example: FILE *fp; char ch; putc (ch,fp);

End of File There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by the fscanf function: FILE *fptr1; int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == feof(fptr1) ) { printf ("End-of-file encountered.\n ) ; }

Reading and Writing Files #include <stdio.h> int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata", "w") ; fprintf (outfile, %f %d %f ", a, b, c) ; fclose (outfile) ; infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ; printf ( %f %d %f \n ", a, b, c) ; printf ( %f %d %f \n ", e, f, g) ; }

Example #include <stdio.h> #include<conio.h> void main() { char ch; FILE *fp; fp=fopen("out.txt","r"); while(!feof(fp)) { ch=getc(fp); printf("\n%c",ch); } getch(); }

fread () Declaration: size_t fread(void *ptr, size_t size, size_t n, FILE *stream); Remarks: fread reads a specified number of equal-sized data items from an input stream into a block. ptr = Points to a block into which data is read size = Length of each item read, in bytes n = Number of items read stream = file pointer

Example Example: #include <stdio.h> int main() { FILE *f; char buffer[11]; if (f = fopen("fred.txt", r )) { fread(buffer, 1, 10, f); buffer[10] = 0; fclose(f); printf("first 10 characters of the file:\n%s\n", buffer); } return 0; }

fwrite() Declaration: size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream); Remarks: fwrite appends a specified number of equal-sized data items to an output file. ptr = Pointer to any object; the data written begins at ptr size = Length of each item of data n =Number of data items to be appended stream = file pointer

Example Example: #include <stdio.h> int main() { char a[10]={'1','2','3','4','5','6','7','8','9','a'}; FILE *fs; fs=fopen("project.txt","w"); fwrite(a,1,10,fs); fclose(fs); return 0; }

fseek() This function sets the file position indicator for the stream pointed to by stream or you can say it seeks a specified place within a file and modify it. SEEK_SET Seeks from beginning of file SEEK_CUR Seeks from current position SEEK_END Seeks from end of file Example: #include <stdio.h> int main() { FILE * f; f = fopen("myfile.txt", "w"); fputs("hello World", f); fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END fputs(" India", f); fclose(f); return 0; }

ftell() offset = ftell( file pointer ); "ftell" returns the current position for input or output on the file #include <stdio.h> int main(void) { FILE *stream; stream = fopen("myfile.txt", "w"); fprintf(stream, "This is a test"); printf("the file pointer is at byte %ld\n", ftell(stream)); fclose(stream); return 0; }