0% found this document useful (0 votes)
45 views30 pages

Week 14 Lectures PDF

This document provides an introduction to file input/output (I/O) in the C programming language. It discusses key concepts like streams, standard streams, opening and closing files, reading and writing files, and command line arguments. The document covers functions for file I/O like fopen(), fclose(), fgets(), fprintf(), getc(), putc(), as well as how to read/write formatted data using fscanf()/fprintf(). It provides examples of opening, reading from, and writing to files in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views30 pages

Week 14 Lectures PDF

This document provides an introduction to file input/output (I/O) in the C programming language. It discusses key concepts like streams, standard streams, opening and closing files, reading and writing files, and command line arguments. The document covers functions for file I/O like fopen(), fclose(), fgets(), fprintf(), getc(), putc(), as well as how to read/write formatted data using fscanf()/fprintf(). It provides examples of opening, reading from, and writing to files in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

EE1102 Introduction to Computer

Programming

File I/O

Devendra Jalihal [email protected]

EE1102 Intro to Comp Prog 1


Homework Problems on Arrays and Strings
• Given a square array of integers – produce an array
rotated clockwise by 90o.
• Convert a string of characters in the range ‘0’ to ‘9’ to
the corresponding integer
– look for minus sign preceding the number
– e.g. “ -986542is ”  the number -986542
• Given an integer, produce the string of characters
denoting that number
– e.g 926  ‘9’, ‘2’, ‘6’
• Given an array of characters, extract a double number
– look for minus sign preceding the number
– e.g “ -63.65” or “ 76.56”

EE1102 Intro to Comp Prog 2


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 in the “header” file <stdio.h>
• You do not need to memorize them, just be
familiar with them
• Programs using the library - portable

EE1102 Intro to Comp Prog 3


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)

EE1102 Intro to Comp Prog 4


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

EE1102 Intro to Comp Prog 5


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

EE1102 Intro to Comp Prog 6


File Access
• Files need to be connected to the program
– the system connects stdin, stdout, and stderr
• Reading from or writing to a file in C requires 3
basic steps:
– open the file
– do all the reading or writing
– close the file
• Internally a file is referred to using a file pointer
– points to a structure that contains info about the file

EE1102 Intro to Comp Prog 7


Opening a File
• Declare a file pointer and open a file using the
function fopen( )
• FILE *fp; /* FILE is a type name, like int */
• Prototype: fopen(char *name, char *mode)

• fp = fopen(name, mode);

what is the file


name of file going to be used
for?
EE1102 Intro to Comp Prog 8
Basic Modes for Opening Files
• ‘r’ – 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.

EE1102 Intro to Comp Prog 9


More File Modes
• ‘r+’ – 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.

EE1102 Intro to Comp Prog 10


An Example
FILE *ifp, *ofp; char *mode = "r";
char inFilename[ ] = “in.list”;
char outFilename[ ] = "out.list"; fopen returns NULL
ifp = fopen(inFilename, mode); if it cannot open a
if (ifp == NULL) { file
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);
exit(1);
}
EE1102 Intro to Comp Prog 11
File Input/Output in C
• getc(*file);
• This function is similar to getchar( ) except that
the input can be from the keyboard or a file.
• Example:
– char ch;
– ch = getc(stdin); /* input from keyboard */
– ch = getc(fileptr); /* input from a file */

EE1102 Intro to Comp Prog 12


… File Input/Output in C
• putc(char, *file);
• This function is similar to putchar( ) except that
the output can be to the screen or a file.
• Example:
– char ch;
– ch = getc(stdin); /* input from keyboard */
– putc(ch, stdout); /* output to the screen */
– putc(ch, outfileptr); /*output to a file */

EE1102 Intro to Comp Prog 13


Formatted Reading and Writing
• fscanf(filepointer, “…”, args);
• fprintf(filepointer, “…”, args);
• Format string and arguments same as with scanf(
) and printf( )

EE1102 Intro to Comp Prog 14


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

EE1102 Intro to Comp Prog 15


Force Write of File Buffer to Disk
• Sometimes it is necessary to forcefully flush a
buffer to its stream:
fflush(outf);

EE1102 Intro to Comp Prog 16


The Function fgets
• One of the alternatives to scanf/fscanf is fgets
• The prototype is:
– char *fgets(char *s, int size, FILE *stream);
– fgets reads in (size – 1) characters from the stream
and stores it into *s pointer
– The string is automatically null-terminated
– Returns s or NULL if there is an error
• fgets stops reading in characters if it reaches an
EOF or NULL
• The string can be scanned using sscanf( )
EE1102 Intro to Comp Prog 17
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);
}
Recall that fgets takes 3 arguments, a string, the maximum
number of characters to read, and a file pointer. It returns
NULL if there is an error (such as EOF).
EE1102 Intro to Comp Prog 18
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 <stdio.h>
int main( )
{
const int MAXLEN=1000;
char readline[MAXLEN];
fgets(readline, MAXLEN, stdin);
printf("You typed %s", readline);
return 0;
}
EE1102 Intro to Comp Prog 19
Command Line Arguments
• Parameters can be passed to C programs by giving
arguments when the program is executed
• Example:
$ echo hello, world prints the output hello, world

$ cat file1 file2 prints contents of file1 followed


by file2
– cat is short for concatenate

EE1102 Intro to Comp Prog 20


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, the program name is the only argument, so
argc =1
• *argv[ ] is a pointer to pointers
– argv[0] is the name of the program
– argv[1] is the first argument, and so on …
– argv[argc] is a null pointer
EE1102 Intro to Comp Prog 21
$echo hello, world
• argc = 3, argv is a pointer to pointers

argv:
echo\0

hello,\0
world\0
0

a two dimensional
array of characters
EE1102 Intro to Comp Prog 22
Implementing echo
#include <stdio.h>
/* echo command 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;
} EE1102 Intro to Comp Prog 23
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;
}
printf((argc > 1) ? “%s ” : “%s”, *++argv);
EE1102 Intro to Comp Prog 24
cat – Reads Files and Prints Them
#include <stdio.h>
main(int argc, char *argv[ ]){
FILE *fp;
void filecopy(FILE *, FILE *)
if (argc == 1) /* no args; copy from stdin */
filecopy(stdin, stdout);
else
/*open the first file, copy it onto screen,
close it, go to next file …. */

EE1102 Intro to Comp Prog 25


cat - Continued
while (--argc > 0)
if ((fp = fopen(*++argv, “r”) == NULL){
printf(“cat: can’t open %s\n”, *argv);
return 1; modify program to direct error messages
} to stderr, so that redirection does not
else { affect it.
cat f1 f2 > outfile
filecopy(fp, stdout);
fclose(fp);
}
return 0;
} /* end of main */

EE1102 Intro to Comp Prog 26


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, ofp);
} copy everything, blanks,
tabs, endofline, till the file
ends

EE1102 Intro to Comp Prog 27


Program Name in Error Message
..
.
char *prog = argv[0];
..
.
if ((fp = fopen(*++argv, “r”)) == NULL){
fprintf (stderr, “%s: can’t open %s\n”, prog,
*argv);
.
.
.

EE1102 Intro to Comp Prog 28


Homework Problem Set 2
• Given two files file1 and file2 of integers, compute the
average of all the numbers, and append file2 at the end
of file1.
• Find the middle element of a string without calculating
the length of the string. (Use pointers)
• Reverse the word order of a sentence using pointers
Example : Chennai is capital of Tamil Nadu
 Nadu Tamil of capital is Chennai
• Given two strings s1 and s2, write a program to say
whether s2 is a rotation of s1?
              Example : Tamilnadu     aduTamiln    True
                               Tamilnadu     dunaTamil    False
EE1102 Intro to Comp Prog 29
A Problem of Managing Indices
• Fill in a rectangular array with increasing numbers in a
spiral form, as shown for the square array

1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
EE1102 Intro to Comp Prog 30

You might also like