CS111 Computer Programming

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.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
File I/O.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
File Handling Spring 2013Programming and Data Structure1.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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:
1 Lecture09: File I/O 11/19/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
Chapter 7 Files By C. Shing ITEC Dept Radford University.
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
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:
C Programming Lecture 12 : File Processing
C File Processing. Objectives To be able to create, write and update files. To become familiar with sequential access file processing. To become familiar.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
Files A collection of related data treated as a unit. Two types Text
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
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.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic properties and characteristics of external files ❏ To.
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.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
External Files: Abstractly, a file can be thought of as a stream of data (either char or binary). C has two groups of files: standard files, such as stdin,
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
Chapter 4 File Processing
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.
Lecture 11 File input/output
TMF1414 Introduction to Programming
Chapter 7 Text Input/Output Objectives
Introduction to Computer Programming Lecture 18 Binary Files
File I/O.
CSC215 Lecture Input and Output.
C Programming:Part 3 Characters and Strings File Processing Exercise.
File Input/Output.
Programming in C Input / Output.
Computer Science 210 Computer Organization
File I/O We are used to reading from and writing to the terminal:
Chapter 11 – File Processing
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
CSC215 Lecture Input and Output.
CSC215 Lecture Input and Output.
Programming and Data Structure
Text and Binary File Processing
File Handling.
Accessing Files in C Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Fundamental of Programming (C)
Programming in C Input / Output.
Chapter 12: File I/O.
File I/O & UNIX System Interface
CS1100 Computational Engineering
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Professor Jodi Neely-Ritz University of Florida
I/O CS580U - Fall 2018.
Professor Jodi Neely-Ritz University of Florida
File I/O We are used to reading from and writing to the terminal:
Files Chapter 8.
Presentation transcript:

CS111 Computer Programming File management in c

Input/Output in C C has no built-in statements for input or output A library of functions is supplied to perform these operations. The I/O library functions are listed the “header” file <stdio.h> You do not need to memorize them, just be familiar with them

Streams All input and output is performed with streams A "stream" is a sequence of characters organized into lines Each line consists of zero or more characters and ends with the "newline" (‘\n’) character ANSI C standard specifies that the system must support lines that are at least 254 characters in length (including the newline character)

Types of Streams in C Every C program has 3 standard streams: Standard input stream is called stdin and is normally connected to the keyboard Standard output stream is called stdout and is normally connected to the display screen. Standard error stream is called stderr and is also normally connected to the screen

Standard Streams in C Input functions normally read from stdin scanf(), gets(), getchar() Output functions normally write to stdout printf(), putchar() I/O Redirection: connect stdin or stdout to a file instead of keyboard or display Type command: myprog scanf reads from keyboard, printf writes to display Type command with file names: myprog < input.dat > output.dat scanf reads from input.dat, printf writes to output.dat

Motivation Handling large volume of data is cumbersome Data lost when program is closed

Basic operations Naming Opening Reading Writing Closing Internally a file is referred to using a file pointer Points to a structure that contains info about the file

Defining and opening a file Filename Data Structure Purpose

Filename It may contain two parts 1. Primary name 2. Optional period with the extension E.g. Input.data Store Prog.c Student.out

Data Structure Defined as FILE in the stdio.h All files should be declared as type FILE before they are used FILE is a defined data type E.g. FILE *fp; Fp = fopen(“filename”, “mode”);

Opening a file Declare a file pointer and open a file using the function fopen() FILE *fp; /* FILE is a typename, like int */ fp = fopen(name, mode); example : fp = fopen(“data.txt”, “r”); name of file what is the file going to be used for?

Basic modes for opening files Open an existing file for reading only. “w” Open the file for writing only. If the file already exists, it is truncated to zero length. Otherwise a new file is created. “a” Open a file for append access; that is, writing at the end of file only. If the file already exists, its initial contents are unchanged and output to the stream is appended to the end of the file. Otherwise, a new, empty file is created.

More file modes “r+” “w+” “a+” Open an existing file for both reading and writing. The initial contents of the file are unchanged and the initial file position is at the beginning of the file “w+” Open a file for both reading and writing. If the file already exists, it is truncated to zero length. Otherwise, a new file is created “a+” Open or create file for both reading and appending. If the file exists, its initial contents are unchanged. Otherwise, a new file is created. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file

An example fopen returns NULL if it cannot open a file FILE *ifp, *ofp; char *mode = "r"; char inFilename[] = “in.list”; char outFilename[] = "out.list"; ifp = fopen(inFilename, mode); if (ifp == NULL) { fprintf(stderr, "Can't open input file %s!\n”, inFilename); exit(1); } ofp = fopen(outFilename, "w"); if (ofp == NULL) { fprintf(stderr, "Can't open output file %s!\n", outFilename); fopen returns NULL if it cannot open a file

Formatted Reading and Writing fscanf(filepointer, “…”, args) fprintf(filepointer, “…”, args) Format string and arguments same as with scanf() and printf() Example: fscanf(fp1, “%d”, &myMarks); fscanf(fp1, “%d”, &myRollNumber); fprintf(fp2, “%d\t%d\n”, myMarks, myRollNumber);

Closing a file When done with a file, it must be closed using the function fclose() fclose(ifp); fclose(ofp); Closing a file is very important, especially with output files. The reason is that output is often buffered. This means that when you tell C to write something out, it doesn't necessary get written to disk right away, but may be stored in a buffer in memory. This output buffer holds the text temporarily When the buffer fills up (or when the file is closed), the data is finally written to disk

Console File Input/ Output Formatted Unformatted Sequential Random scanf(), printf() Unformatted getchar(), putchar(), gets(), puts() File Sequential fprintf(), fscanf() Random fseek(), ftell(), rewind()

Binary file I/O Mode Binary file is merely a collection of bytes Read mode: “rb” Write mode: “wb”

Writing a record Writing Reading

Record I/O Revisited The numbers (basic salary) would occupy more number of bytes, since the file has been opened in text mode. This is because when the file is opened in text mode, each number is stored as a character string. If the number of fields in the structure increase (say, by adding address, house rent allowance etc.), writing structures is cumbersome

fwrite() Address of the structure Size of the structure in bytes Number of records to be written Pointer to the file we want to write to

fread() Address of the structure Size of the structure in bytes Number of records to be written Pointer to the file we want to write to

Manipulating data record Add record Read record Search for a record Delete Record Edit Record

fseek(), rewind(), ftell() int fseek(FILE *stream, long int offset, int whence) void rewind(FILE *stream) long int ftell(FILE *stream) SEEK_SET: Beginning of file SEEK_CUR: Current position of the file pointer SEEK_END: End of file

Command line arguments Parameters can be passed to C programs by giving arguments when the program is executed examples > echo hello, world prints the output hello, world > cat file1 file2 prints contents of file1 followed by file2

main(int argc, char *argv[]) The main program in C is called with two implicit arguments argc and argv argc is an integer value for the number of arguments in the command line if none then argc =1 the program name is the only argument *argv[] is a pointer to a pointer an array of strings argv[0] is the name of the program argv[1] is the first argument. argv[2] is the next … and so on… argv[argc] is a null pointer

echo hello world argv: echo\0 hello\0 world\0 a two dimensional array of characters argc = 3, argv is a pointer to pointers

implementing echo #include <stdio.h> /* echo comand line arguments: 1st version */ main(int argc, char *argv[]) { int i; for (i = 1; i < argc; i++) printf(“%s ”, argv[i]); printf(“\n”); return 0; }

implementing echo #include <stdio.h> /* echo comand line arguments: 1st version */ main(int argc, char *argv[]){ int i; for (i = 1; i < argc; i++) printf(“%s%s”, argv[i], (i < argc - 1) ? “ ” : “”); printf(“\n”); return 0; }

echo – pointer version #include <stdio.h> /* echo comand line arguments: 2nd version */ main(int argc, char *argv[]) { while (--argc > 0) printf(“%s%s”, *++argv, (argc > 1) ? “ ” : “”); printf(“\n”); return 0; }

copying a file /* filecopy: copy file ifp to file ofp */ void filecopy(FILE *ifp, FILE *ofp) { int c; while ((c = getc(ifp)) != EOF) putc(c, cfp); } copy everything, blanks, tabs, endofline, till the file ends

Program name in error message … char *prog = argv[0]; if ((fp = fopen(*++argv, “r”)) == NULL) { fprint(stderr, “%s: can’t open %s\n”, prog, *argv);