C Basic File Input/Output Manipulation. - 1 - C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.

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

C Programming lecture 2 Beautiful programs Greek algorithms
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
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,
Character String Manipulation. Overview Character string functions sscanf() function snprintf() function.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
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.
C Programming - Lecture 5
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.
Chapter 10.
Programming in C #2 Input / Output.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
V-1 University of Washington Computer Programming I File Input/Output © 2000 UW CSE.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
C Programming - Lecture 6 This lecture we will learn: –Error checking in C –What is a ‘wrappered function’? –What is a clean interface? –How to earn your.
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.
File IO and command line input CSE 2451 Rong Shi.
CSEB114: Principle of programming Chapter 11: Data Files & File Processing.
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:
Lecture 8a: File I/O BJ Furman 21MAR2011. Learning Objectives Explain what is meant by a data stream Explain the concept of a ‘file’ Open and close files.
Introduction As programmers, we don’t want to have to implement functions for every possible task we encounter. The Standard C library contains functions.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
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.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
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:
CS 261 – Recitation 7 Spring 2015 Oregon State University School of Electrical Engineering and Computer Science.
Chapter 15 Strings as Character Arrays
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Files A collection of related data treated as a unit. Two types Text
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.
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.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
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.
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
A bit of C programming Lecture 3 Uli Raich.
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.
Chapter 7 Text Input/Output Objectives
An Introduction to C Programming
File I/O.
Plan for the Day: I/O (beyond scanf and printf)
Programming and Data Structures
File Input/Output.
Programming in C Input / Output.
Programming in C Input / Output.
Files I/O, Streams, I/O Redirection, Reading with fscanf
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Beginning C Lecture 11 Lecturer: Dr. Zhao Qinpei
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
FILE HANDLING IN C.
Programming and Data Structure
File Input and Output.
File Handling.
Programming in C Input / Output.
C Characters and Strings
C Programming - Lecture 3
CSc 352 File I/O Saumya Debray Dept. of Computer Science
I/O CS580U - Fall 2018.
Presentation transcript:

C Basic File Input/Output Manipulation

- 1 - C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files. v Special file streams stdin, stdout & stderr. v How we SHOULD read input from the user. v What are STRUCTURES? v What is dynamic memory allocation?

- 2 - 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 */ }

- 3 - Modes for opening files  The second argument of fopen is the mode in which we open the file. There are three v "r" opens a file for reading v "w" opens a file for writing - and writes over all previous contents (deletes the file so be careful!) v "a" opens a file for appending - writing on the end of the file

- 4 - The exit() function v Sometimes error checking means we want an "emergency exit" from a program. We want it to stop dead. v In main we can use "return" to stop. v 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

- 5 - Writing to a file using fprintf v fprintf works just like printf and sprintf except that its first argument is a file pointer. v 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");

- 6 - Reading from a file using fgets v fgets is a better way to read from a file v 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)

- 7 - Closing a file v 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);

- 8 - Open and Close v 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 (fptr);

- 9 - 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) v What might this do: fprintf (stdout,"Hello World!\n");

Reading loops v 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. /* define MAXLEN at start using enum */ FILE *fptr; char tline[MAXLEN]; /* A line of text */ fptr= fopen ("sillyfile.txt","r"); /* check it's open */ while (fgets (tline, MAXLEN, fptr) != NULL) { printf ("%s",tline); // Print it } fclose (fptr);

Using fgets to read from the keyboard v 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; }

Getting numbers from strings  Once we've 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

Issues v fgets includes the '\n' on the end v This can be a problem - for example if in the last example we got input from the user and tried to use it to write a file: FILE *fptr; char readfname[1000]; fgets (readfname,1000,stdin); fptr= fopen (readfname,"w"); /* oopsie - file name also has \n */ Even experienced programmers can make this error

Dynamic memory allocation v How would we code the "sieve of Eratosthenes" to print all primes between 1 and n where the user chooses n? v We _could_ simply define a HUGE array of chars for the sieve - but this is wasteful and how big should HUGE be? v The key is to have a variable size array. v In C we do this with DYNAMIC MEMORY ALLOCATION

A dynamically allocated sieve #include void vary_sieve (int); void vary_sieve (int n) /* Sieve to find all primes from 1 - n */ { char *sieve; int i; sieve= (char *)malloc (n*sizeof(char)); /* check memory here */ for (i= 0; i < n; i++) sieve[i]= UNCROSSED; /* Rest of sieve code */ free (sieve); /* free memory */ }

A closer look at malloc v Let's look at that malloc statement again: sieve= (char *)malloc(n*sizeof(char)); sizeof(char) returns how much memory a char takes we want n chars This is a CAST (remember them) that forces the variable to the right type (not needed) This says in effect "grab me enough memory for 'n' chars"

Free v The free statement says to the computer "you may have the memory back again" free(sieve); essentially, this tells the machine that the memory we grabbed for sieve is no longer needed and can be used for other things again. It is _VITAL_ to remember to free every bit of memory you malloc

Check the memory from malloc v Like fopen, malloc returns NULL if it has a problem v Like fopen, we should always check if malloc manages to get the memory. float *farray; /* Try to allocate memory for 1000 floats */ farray= malloc(1000*sizeof(float)); if (farray == NULL) { fprintf (stderr, "Out of memory!\n"); exit (-1); }

C++ Input and Output v Variety of I/O functions in C++ iostream Library.  Must include to use them. v Must use g++ to compile  cout << “Hello world\n”;  cin >> x; »Read into variable x;