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

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

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

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

C Programming Language

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

Computer Programming Unit v

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

File Handling. Reference:

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

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Organization of a file

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

25.2 Opening and Closing a File

EM108 Software Development for Engineers

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

C-Refresher: Session 10 Disk IO

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

Computer System and programming in C

PROGRAMMAZIONE I A.A. 2017/2018

Input / Output Functions

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

2009 S2 COMP File Operations

ENG120. Misc. Topics

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

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

Standard File Pointers

Ch 11. C File Processing (review)

Introduction to file management

File IO and command line input CSE 2451

Input/Output: Advanced Concepts

Computer programming

CE Lecture 11

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

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

Lecture 9: File Processing. Quazi Rahman

Intermediate Programming, Spring 2017*

Chapter 11 File Processing

Input/Output and the Operating Systems

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

Chapter 10. File Processing 248 FILE PROCESSING

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

M.CS201 Programming language

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

CS240: Programming in C

System Software Experiment 1 Lecture 7

Standard C Library Functions

Programming Fundamentals

C File Processing: One-Page Summary

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

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

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

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

Programming & Data Structure

Today s Learning Objectives

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

8. Characters, Strings and Files

Data File and File Handling

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

IO = Input & Output 2

Lecture6 File Processing

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

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

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

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

Introduction to string

C programming basics T3-1 -

UNIX System Programming

Pointers and File Handling

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.

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

C Basics And Concepts Input And Output

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

File Handling. 21 July 2009 Programming and Data Structure 1

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

8. Structures, File I/O, Recursion. 18 th October IIT Kanpur

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

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.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING UNIT-1

Computers Programming Course 5. Iulian Năstac

HIGH LEVEL FILE PROCESSING

Chapter 8: Character & String. In this chapter, you ll learn about;

Introduction to Computer Programming Lecture 18 Binary Files

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

File I/O. Preprocessor Macros

211: Computer Architecture Summer 2016

mywbut.com 12 File Input/Output

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

Strings. Steven R. Bagley

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

Advanced C Programming and Introduction to Data Structures

Chapter 14 - Advanced C Topics

The fopen command can open an external file in C language. If the file is exist, the file pointer is not NULL. Otherwise, the file pointer is NULL.

Lecture 03 Bits, Bytes and Data Types

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

Basic and Practice in Programming Lab 10

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

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

High Performance Programming Programming in C part 1

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

C: How to Program. Week /June/18

Transcription:

1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard disk, pen drive, and tape. There are two kinds of files that programmers deal with text files and binary files. Text file are human readable and it is a stream of plain English characters. Binary files are not human readable. It is a stream of processed characters and ASCII symbols. 2. Explain File opening mode. We want to open file for some purpose like, read file, create new file, append file, read and write file, etc When we open any file for processing, at that time we have to give file opening mode. We can do limited operations only based on mode in which file is opened. e.g. fp = fopen( demo.txt, r ); //Here file is opened in read only mode. C has 6 different file opening modes for text files: 1) r open for reading only. 2) w open for writing (If file exists then it is overwritten) 3) a open for appending (If file does not exist then it creates new file) 4) r+ open for reading and writing, start at beginning 5) w+ open for reading and writing (overwrite file) 6) a+ open for reading and writing, at the end (append if file exists) Same modes are also supported for binary files by just adding b, e.g. rb, wb, ab, r+b, w+b, a+b 3. Write a C program to display file on screen. #include <stdio.h> void main() FILE *fp; // fp is file pointer. FILE is a structure defined in stdio.h char ch ; fp = fopen( prog.c, r ); // Open prog.c file in read only mode. ch = getc(fp) ; while (ch!= EOF) // EOF = End of File. Read file till end fclose(fp); 4. Write a C program to copy a file. #include <stdio.h> void main() FILE *p,*q; char ch; putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character // Close the file so that others can access it. 1

p = fopen( Prog.c,"r"); q = fopen( Prognew.c,"w"); ch = getc(p); while(ch!= EOF) putc(ch,q); ch = getc(p); printf("file is copied successfully. "); fclose(p); fclose(q); return 0; 5. Explain file handing functions with example. C provides a set of functions to do operations on file. These functions are known as file handling functions. Each function is used for some particular purpose. 1) fopen() (Open file) fopen is used to open a file for operation. Two arguments should be supplied to fopen function, File name or full path of file to be opened File opening mode which indicates which type of operations are permitted on file. If file is opened successfully, it returns pointer to file else NULL. fp = fopen( Prog.c, r ); // File name is prog.c and it is opened for reading only. 2) fclose() (Close file) Opened files must be closed when operations are over. The function fclose() is used to close the file i.e. indicate that we are finished processing this file. To close a file, we have to supply file pointer to fclose() function. If file is closed successfully then it returns 0 else EOF. fclose(fp); 3) fprintf() (Write formatted output to file) The fprintf() function prints information in the file according to the specified format. fprintf() works just like printf(), only difference is we have to pass file pointer to the function. It returns the number of characters outputted, or a negative number if an error occurs. fprintf(fp, Sum = %d, sum); 4) fscanf() (Read formatted data from file) The function fscanf() reads data from the given file. It works in a manner exactly like scanf(), only difference is we have to pass file pointer to 2

the function. If reading is succeeded then it returns the number of variables that are actually assigned values, or EOF if any error occurred. fscanf(fp, %d, &sum); 5) fseek() (Reposition file position indicator) Sets the position indicator associated with the file pointer to a new position defined by adding offset to a reference position specified by origin. You can use fseek() to move beyond a file, but not before the beginning. fseek() clears the EOF flag associated with that file. We have to supply three arguments, file pointer, how many characters, from which location. It returns zero upon success, non-zero on failure. The origin value should have one of the following values Name Explanation SEEK_SET Seek from the start of the file SEEK_CUR Seek from the current location SEEK_END Seek from the end of the file fseek(fp,9,seek_set); // Moves file position indicator to 9 th position from begging. 6) ftell() (Get current position in file) It returns the current value of the position indicator of the file. For binary streams, the value returned corresponds to the number of bytes from the beginning of the file. position = ftell (fp); 7) rewind() (Set position indicator to the beginning) Sets the position indicator associated with file to the beginning of the file. A call to rewind is equivalent to: fseek (fp, 0, SEEK_SET); On file open for update (read+write), a call to rewind allows to switch between reading and writing. rewind (fp); 8) getc() (Get character from file) getc function returns the next character from file or EOF if the end of file is reached. After reading a character, it advances position in file by one character. getc is equivalent to getchar(). fgetc is identical to getc. ch = getc(fp); 9) putc() (Write character to file) putc writes a character to the file and advances the position indicator. After reading a character, it advances position in file by one character. If there are no errors, the same character is returned; if error occurs then EOF is returned. 3

putc is equivalent to putchar(). fgetc is identical to putc. putc(ch, fp); 10) getw() (Get integer from file) getw function returns the next int from the file. If error occurs then EOF is returned. i = getw(fp); 6. 11) putw() (Write integer to file) putw function writes integer to file and advances indicator to next position. It succeeded then returns same integer otherwise EOF is returned. putw(i, fp); 12) feof() feof() function returns non-zero value only if end of file has reached otherwise it returns 0. Example : feof(fp) Write a program to count the number of lines, number of tabs, characters and words in a given file. #include <stdio.h> void main() FILE *fp; int lines=0, tabs=0, characters=0, words = 0; char ch, filename[100] ; printf( Enter file name: ); gets( filename ); // You can also use scanf( %s,filename); fp = fopen( filename, r ); if ( fp == NULL ) // File is not opened successfully then it returns NULL. printf( Cannot open %s for reading \n, filename ); exit(1); /* terminate program */ ch = getc( fp ); while ( ch!= EOF ) if ( ch == \n ) lines++ ; else if ( ch == \t ) tabs ++ ; else if ( ch == ) words ++ ; else characters++; c = getc ( fp ); 4

fclose( fp ); printf( Lines=%d Tabs=%d Words=%d Characters=%d, lines, tabs, words, characters); 7. What is difference between Static Memory Allocation and Dynamic Memory Allocation Static Memory Allocation If memory is allocated to variables before execution of program starts then it is called static memory allocation. Dynamic Memory Allocation If memory is allocated at runtime (during execution of program) then it is called dynamic memory. It is fast and saves running time. It is bit slow. It allocates memory from stack. It allocates memory from heap It is preferred when size of an array is known in advance or variables are required during most of the time of execution of program. Allocated memory stays from start to end of program. The storage space is given symbolic name known as variable and using this variable we can access value. It is preferred when number of variables is not known in advance or very large in size. Memory can be allocated at any time and can be released at any time. The storage space allocated dynamically has no name and therefore its value can be accessed only through a pointer. 8. Explain Storage classes. Storage class decides the scope, lifetime and memory allocation of variable. Scope of a variable is the boundary within which a variable can be used. Four storage classes are available in C, 1) Automatic (auto) 2) Register (register) 3) External (extern) 4) Static (static) 1) automatic: Variables which are declared in function are of automatic storage class. Automatic variables are allocated storage in the main memory of the computer. Memory is allocated automatically upon entry to a function and freed automatically upon exit from the function. The scope of automatic variable is local to the function in which it is declared. It is not required to use the keyword auto because by default storage class within a block is auto. int a; auto int a; 5

6 2) register: Automatic variables are allocated storage in the main memory of the computer; However, for most computers, accessing data in memory is considerably slower than processing directly in the CPU. Register variables are stored in registers within the CPU where data can be stored and accessed quickly. Variables which are used repeatedly or whose access time should be fast may be declared to be of storage class register. Variables can be declared as a register: register int var; 3) external: Automatic and register variables have limited scope and limited lifetimes in which they are declared. Sometimes we need global variables which are accessible throughout the program. extern keyword defines a global variable that is visible to ALL functions. extern is also used when our program is stored in multiple files instead of single file. Memory for such variables is allocated when the program begins execution, and remains allocated until the program terminates. Memory allocated for an external variable is initialized to zero. Declaration for external variable is as follows: extern int var; 4) static: static keyword defines a global variable that is visible to ALL functions in same file. Memory allocated for static variable is initialized to zero. Static storage class can be specified for automatic as well as external variables such as: static extern int varx; //static external static int var; // static automatic Static automatic variables continue to exist even after the function terminates. The scope of static automatic variables is identical to that of automatic variables. 9. Explain Input / Output functions. 1) scanf( ) It is used to read all types of data. It cannot read white space between strings. It can read multiple data at a time by multiple format specifier in one scanf( ). scanf( %d%d, &a, &b); 2) printf( ) It is used to display all types of data and messages. It can display multiple data at a time by multiple format specifier in one printf( ). printf( a=%d b=%d, a, b); Unformatted input output functions 1) gets()

7 It is used to read a single string with white spaces. It is terminated by enter key or at end of line. char str[10]; gets(str); 2) getchar(), getche( ), getch( ) It is used to read single character at a time. getchar( ) function requires enter key to terminate input while getche( ) and getch( ) does not require. getch( ) function does not display the input character while getchar( ) and getche( ) function display the input character on the screen. char ch; ch = getchar(); ch = getche(); ch = getch(); 3) puts() It is used to display a string at a time. char str[]= Hello ; puts(str ); 4) putchar() It is used to display single character at a time. putchar(ch); Character checking functions. Character checking functions are available in ctype.h header file. 1) isdigit(int); for checking number (0-9) 2) isalpha(int); for checking letter (A-Z or a-z) 3) isalnum(int); for checking letter (A-Z or a-z) or digit (0-9) 4) isspace(int); for checking empty space 5) islower(int); for checking letter (a-z) 6) isupper(int); for checking letter (A-Z) 7) ispunct(int); for checking punctuation symbols (like - :, ;,,,?,. etc. ) 10. Write a program to check the entered character is digit or not #include<stdio.h> #include<conio.h> #include<ctype.h> void main() char c; clrscr(); scanf("%c",&c);

if(isdigit(c)) printf("true"); getch(); 11. Explain command-line argument with example. Command-line arguments are given after the name of a program in command line operating systems like DOS or Linux. Up to this point there is no argument in main() function. main() can accept two arguments : 1) First argument is number of command-line arguments. 2) Second argument is a full list of command-line argument. Syntax: int main(int argc, char *argv[]) Here argc refers to the number of arguments passed and argv[] is a pointer array which point to each argument which passed to main. Following is a simple example which checks if there is any argument supplied from the command-line and take action accordingly: #include <stdio.h> int main( int argc, char *argv[] ) if( argc == 2 ) printf("the argument supplied is %s\n", argv[1]); else if( argc > 2 ) printf("too many arguments supplied.\n"); else printf("one argument expected.\n"); Here argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one and if you pass one argument then argc is set at 2. You pass all the command-line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes "" or single quotes. $./a.out testing1 testing2 Too many arguments supplied. 8