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.

Slides:



Advertisements
Similar presentations
C: Advanced Topics-II Winter 2013 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
Advertisements

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.
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: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
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,
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Structures and Unions Chapter 6. Structure A structure is an aggregate data type  Composed of two or more related variables called member/field/element.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
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.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Programming Practice Introduction Tree Operations. Binary Search Tree. File Processing Create, read, write and update files. Sequential.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
File IO and command line input CSE 2451 Rong Shi.
Chapter 8 File-Oriented Input and Output. 8.1 INTRODUCTION a file can also be designed to store data. We can easily update files, A data file as input.
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 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Data files –Can be created, updated, and processed by C programs –Are used for permanent.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
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.
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
CS 261 – Recitation 7 Spring 2015 Oregon State University School of Electrical Engineering and Computer Science.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
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.
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.
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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
C for Java Programmers Tomasz Müldner Copyright:  Addison-Wesley Publishing Company, 2000 The next lecture is on Tue, in Auditorio
11 C File Processing.
TMF1414 Introduction to Programming
Chapter 7 Text Input/Output Objectives
File Access (7.5) CSE 2031 Fall July 2018.
File I/O.
CS 261 – Recitation 7 Fall 2013 Oregon State University
CS111 Computer Programming
File Input/Output.
Programming in C Input / Output.
What you need for the 1st phase of project
Chapter 11 – File Processing
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
FILE HANDLING IN C.
Programming and Data Structure
Text and Binary File Processing
File Input and Output.
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.
EPSII 59:006 Spring 2004.
C Programming - Lecture 3
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

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 and is usually based on some kind of durable storage such as the Hard disc. Is a block of arbitrary information, or resource for storing information, which is available to a computer program and is usually based on some kind of durable storage such as the Hard disc.

Types of File Text Files Binary Files

File Processing For read from or write to a file you should do the following: You MUST open the file and specify the opening mode: read, write, append, … etc. You can perform the required operation (read or write) after that. You have to close the file after you finish the task.

File Processing You can declare the file pointer (binary of text) as the following: FILE *f1;  f1 is a pointer You can open the file by the following statement: f1 = fopen(“file path”, “opening mode”); Examples: f1 = fopen (“c:\\myfile.txt”, “rt”);  This opens a Text File with the name “myfile.txt” in the root of drive C for Reading Text data.

Modes for opening files The second argument of fopen is the mode in which we open the file. There are three "r" opens a file for reading "w" opens 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

File Processing Examples (contd.): f1 = fopen (“c:\\myfile.uuu”, “wt”);  This opens a Text File with the name “myfile.uuu” in the root of drive C for Writing Text data. f1 = fopen (“c:\\myfile.xxx”, “rb”);  This opens a Binary File with the name “myfile.xxx” in the root of drive C for Reading Binary data. f1 = fopen (“c:\\myfile.abc”, “wb”);  This opens a Binary File with the name “myfile.abc” in the root of drive C for Writing Binary data.

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 couldn't open the file. FILE *fptr; char filename[]= "file2.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { fprintf (stderr, “ERROR”); /* DO SOMETHING */ }

File Processing You can use fprintf and fscanf to write to or read from a Text File respectively. You can use fwrite and fread to write to or read from a Binary File respectively. close the file by the following statement: fclose(f1);

Text Files Used to store data as text. fprintf is used to write data to a text file. fprintf ([file pointer], [formatting sting], [arg1], [arg2], …) fscanf is used to read data from a text file. fscanf ([file pointer], [formatting sting], [&arg1], [&arg2], …)

Writing to a file using fprintf fprintf works just like printf and sprintf except that its first argument is a file pointer. We could also read numbers from a file using fscanf – but there is a better way. FILE *fptr; fptr= fopen ("file.dat","w"); /* Check it's open */ fprintf (fptr,"Hello World!\n");

Example 1 void main(void) { FILE *f1; float x=5.346; char cc[] = “Hello”; f1 = fopen(“c:\\abc.txt”, “wt”); fprintf( f1, “%s %f”, cc, x); fclose(f1); }

Example 2 void main(void) { FILE *f1; float x; char cc[100]; f1 = fopen(“c:\\abc.txt”, “rt”); fscanf( f1, “%s %f”, cc, &x); fclose(f1); }

Example 3 void main(void) { FILE *f1, *f2; char c; f1 = fopen(“c:\\abc.txt”, “rt”); f2 = fopen(“c:\\abc_copy.txt”, “wt”); while(!feof(f1)) { fscanf( f1, “%c”, &c); fprintf( f2, “%c”, c); } fclose(f1); fclose(f2); }

Example 4 struct Pers_Data { char Name[100]; int ID; char Add[255]; }; void main(void) { Pers_Data P[10]; FILE *f; int i; for( i = 0; i<10; i++) { scanf(“%s”, P[i].Name); scanf(“%d”, &P[i].ID); scanf(“%s”, P[i].Add); } f = fopen(“c:\\DataBase.1”, “wt”); for( i = 0; i<10; i++) { fprintf(f, “%s”, P[i].Name); fprintf(f, “%d”, P[i].ID); fprintf(f, “%s”, P[i].Add); } }//main

16 Files and Streams Read/Write functions in standard library fgetc Reads one character from a file Takes a FILE pointer as an argument fgetc( stdin ) equivalent to getchar() fputc Writes one character to a file Takes a FILE pointer and a character to write as an argument fputc( 'a', stdout ) equivalent to putchar( 'a' ) fgets Reads a line from a file fputs Writes a line to a file fscanf / fprintf File processing equivalents of scanf and printf

Reading from a file using fgets fgets is a better way to read from a file We can read into 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, a maximum number of characters to read and a file pointer. It returns NULL if there is an error (such as EOF)

Closing a file We can close a file simply using fclose and the file pointer. Here's a complete "hello files". 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);

Great Muck-Ups in C #72 of 100 We use the file pointer to close the file - not the name of the file FILE *fptr; fptr= fopen ("myfile.dat","r"); /* Read from file */ fclose ("myfile.dat"); /* Ooops - that's wrong */

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");

Using fgets to read from the keyboard fgets and stdin can be combined to get a safe way to get a line of input from the user #include int main() { const int MAXLEN=1000; char readline[MAXLEN]; fgets (readline,MAXLEN,stdin); printf ("You typed %s",readline); return 0; }

Example Write a program that contains a function that will be given a text file, count the number of words in this file and return this count.

Example Implement a database that manages the information of employees in a company. These data are Name (struct of first name, middle name, last name) Date Of Birth (DOB) (struct of day, month and year) Address (struct of street, city, country) Contacts (struct of telephone number, mobile number, address)

Salary (struct of basic, additional, reductions, taxes) The database program should do the following tasks: (a) Input employee information and check for correctness of fields as necessary.

(b) Append new employee data to the database file using a function called Insert_Emp. This function should check if the same name of the employee not exists before updating or otherwise it will message “Already exists” without appending the new information. (c) Modify an existing employee data using a function called Update_Emp. This function should check if the same name of the employee not exists before updating or otherwise it will message “Already exists” without saving the updated information. (d) Delete the information of an employee using a function called Del_Emp. This function should message “are you sure?”

(e) Search for an employee with Name or DOB or Telephone number or Mobile number. (f) Be able to sort employees according to Name or DOB or Salary.

Binary Files There are up to 100 students, every student has name, up to 10 grades, the actual number of grades is stored, and the gpa : #define STUDENTSN 100 #define MARKSN 10 #define NAMELENN 20 typedef struct { char name[NAMELENN+1]; int marksNumber; double marks[MARKSN]; double gpa; } StudentT; StudentT info[STUDENTSN];

saveStudent /* Purpose: write number structures, contained in the * array info, to the file fname. * Returns: 1 if successful; otherwise 0 */ int saveStudent(const char *fname, StudentT info[], int number) { FILE *out; if((out = fopen(fname, "wb")) == NULL) return 0; if(fwrite(info,sizeof(StudentT),number,out)!=number ){ fclose(out); return 0; } if(fclose(out) == EOF) return 0; return 1; }

Binary Files Used to store data as binary. fwrite is used to write data to a binary file. fwrite ([&arg], [arg size], [number of arg.], [file pointer]) fread is used to read data from a binary file. fread ([&arg], [arg size], [number of arg.], [file pointer])

updateGpa / * Purpose: initialize all of the gpa fields; * reading data from a file and then * writing them back to this file */ int updateGpa(const char *fname) { FILE *inOut; StudentT buffer; int i; if((inOut = fopen(fname, "r+b")) == NULL) return 0; /* read one structure at a time */ while(fread(&buffer,sizeof(StudentT),1,inOut)!= 0) { for(i =0, buffer.gpa = 0.0; i < buffer.marksNumber; i++) /* compute gpa */ buffer.gpa += buffer.marks[i];

Example 5 void main(void) { FILE *f1; float x=5.346; char cc[] = “Hello”; f1 = fopen(“c:\\abc.bin”, “wb”); fwrite(&x, sizeof(float), 1, f1); fwrite(cc, sizeof(char), strlen(cc), f1); fclose(f1); }

Example 6 void main(void) { FILE *f1; float x; char cc[100]; f1 = fopen(“c:\\abc.bin”, “rb”); fread(&x, sizeof(float), 1, f1); fread(cc, sizeof(char), 5, f1); fclose(f1); }

Example 7 void main(void) { FILE *f1, *f2; char c; f1 = fopen(“c:\\abc.bin”, “rb”); f2 = fopen(“c:\\abc_copy.bin”, “wb”); while(!feof(f1)) { fread(&c, sizeof(char), 1, f1); fwrite(&c, sizeof(char), 1, f2); } fclose(f1); fclose(f2); }

Example 8 struct Pers_Data { char Name[100]; int ID; char Add[255]; }; void main(void) { Pers_Data P[10]; FILE *f; int i; for( i = 0; i<10; i++) { scanf(“%s”, P[i].Name); scanf(“%d”, &P[i].ID); scanf(“%s”, P[i].Add); } f = fopen(“c:\\DataBase.2”, “wb”); for(i = 0; i<10; i++) fwrite(&P[i], sizeof(Pers_Data), 1, f); }//main

Example 9 struct Pers_Data { char Name[100]; int ID; char Add[255]; }; void main(void) { Pers_Data P[10]; FILE *f; int i; for( i = 0; i<10; i++) { scanf(“%s”, P[i].Name); scanf(“%d”, &P[i].ID); scanf(“%s”, P[i].Add); } f = fopen(“c:\\DataBase.3”, “wb”); fwrite(P, sizeof(Pers_Data), 10, f); }//main

Example5 Write a 12-hour clock program that declares a clock struct to store hours, minutes, seconds, A.M. and P.M. provide functions to perform the following tasks: Write a 12-hour clock program that declares a clock struct to store hours, minutes, seconds, A.M. and P.M. provide functions to perform the following tasks: Allow the clock to tick by advancing the seconds by one and at the same time correcting the hours and minutes for a 12- hour clock value of AM or PM Allow the clock to tick by advancing the seconds by one and at the same time correcting the hours and minutes for a 12- hour clock value of AM or PM

Member Access through Pointer If p is a pointer to a structure that has a member w, then p->w gives access to w. Memory Allocation for a Structure For a structure s and a pointer p to this structure, use: if((p = malloc(sizeof(struct s)) == NULL) …

Linked Lists A list is a collection of elements; each element contains data; here double values: typedef double DataType; typedef struct elem { DataType value; struct elem *next; } ElemT, *ElemTP; The value of next will be NULL if there is no next element, otherwise it will be a structure representing the next element.

Linked Lists: delete (cont.) for(aux = this->first; aux->next->next != NULL; aux = aux->next) ; /* the predecessor of last element */ *value = aux->next->value; free(aux->next); aux->next = NULL; return 1; }

Linked Lists: delete int deleteFirst(ListTP this) { ElemTP aux = this->first; if(aux == NULL) /* empty list */ return 0; this->first = aux->next; free(aux); return 1; } void clear(ListTP this) { while(deleteFirst(this)) ; this->first = NULL; }

Unions struct intAndDouble { union intOrDouble { int i; int i; double d; double d; }; };

Left Shift Left shift: i << j The resulting word will have all bits shifted to the left by j positions; for every bit that is shifted off the left end of the word, there is a zero bit added at the right end. x <<= 1 is equivalent to x *= 2 x <<= 2 is equivalent to x *= 4.

Right Shift Right shift: i >> j The resulting word will have all bits shifted to the right by j positions; for every bit that is shifted off the right end of the word, there is a zero bit added at the left end. x >>= 1 is equivalent to x /= 2 x >>= 2 is equivalent to x /= 4.

The End