COMS11500: Introduction To C
COMS11500: Introduction To C
26 Nov, 2013
In previous lectures
Task
Given a file data.in containing integers,
1 read the integers in the file,
2 modify these integers so their Luhn checksum works out,
3 and write the modified integers to data.out
Problem
Fixing Luhn check digits
Task
Given a file data.in containing integers,
1 read the integers in the file,
2 modify these integers so their Luhn checksum works out,
3 and write the modified integers to data.out
Skills needed
How to read from and write to files
How to reuse existing code (e.g. in numbers.cpp) for our own
purposes (i.e. to fix the Luhn checksum)
File input/output
Outline
1 File input/output
Introductory comments
Programs must be able to write data to files or to physical output
devices, such as displays or printers, and to read in data from files or
input devices such as a keyboard.
The C standard library provides numerous functions for these
purposes. The part of the standard library devoted to these
input/output operation is often referred to as the I/O library.
All of the basic functions, macros, and types for input and output are
declared in the header file stdio.h
Apart from these library functions, the C language itself contains no
input or output support at all.
The I/O functionality of C is fairly low-level by modern standards.
File input/output
Streams
From the point of view of a C program, input and output operations,
whether to or from physical devices (e.g. screens and keyboards), or
whether to or from files on storage devices (e.g. hard disks), are
mapped onto logical data streams
A stream can be thought of as a channel, by which data can flow to
the program (input streams), or from the program (output
streams).
The stream model of file I/O was popularized by the Unix operating
system, which was developed concurrently with the C programming
language itself.
According to the type of data transmitted through streams, we can
distinguish between text streams and binary streams.
File input/output
Text streams
A text stream is a sequence of bytes, which are mapped onto ASCII
characters and collectively form human-readable text.
The text is divided into lines, each consisting of zero or more
characters plus a terminating newline character.
Lines can be empty, i.e. they consist of the newline character only.
The last line in the stream may or may not have a newline character,
depending on the implementation.
File input/output
Binary streams
A binary stream is a sequence of bytes without any modification (i.e.
no mapping to ASCII or other type of code is performed).
The data transmitted through a binary stream are not readable by
humans (unlike text streams)
Because no mapping is taking place, operations on binary streams are
generally faster and occupy less space than text streams.
Here, we focus on text streams
File input/output
Standard streams
When a C program starts executing, three standard text streams are
created and they become availble to the program:
Standard input (stdin): usually associated with the keyboard; used by
scanf to read data.
Standard output (stdout): usually associated with the screen; used by
printf to write data.
Standard error (stderr): used for outputing error messages; default
behaviour usually indistinguishable from stdout.
The associations of these streams with devices can be modifed (i.e.
streams can be redirected)
File input/output
Files
A file is a pool of data (bytes), which can be associated with (and
controlled by) a stream
From the point of view of C (and Unix), stored files and devices are
both just files (e.g. disk files and device files), which can be accessed
uniformly through streams.
There are text files and binary files
The association between a file and a stream results in the creation of
a data structure of type FILE (defined in stdio.h).
The programmer uses a pointer to this structure (i.e. FILE *) to
control the stream and read to or write from the file.
The variables stdin, stdout and stderr we saw earlier are actually
pointers to dierent FILE structures!
File input/output
File Input/Output
An overview
Start
Open
Golden Rules
no
Succeeded? report 1 Test if opening your files was successful
yes
2 Test for terminating conditions (e.g.
read/write
end of file)
no
Done?
3 Do not forget to close your files once
yes
done!
close
End
File input/output
Opening a file
FILE *fopen(char *filename, char *mode);
Declared in <stdio.h>, opens file and links it to a stream
mode is up to 3 characters long, indicates permitted operations:
r read only (returns NULL, if file not found)
w write only (erases file if it exists, creates it otherwise)
a append only (creates file if necessary)
Add a + for both reading and writing, e.g. r+
Add a b for binary files, e.g. rb or r+b.
Always use double-quotes!
Closing a file
Note:
Upon exit of the program, all buers all flushed and files are closed
If program exits abnormally, you might lose data (because of unflushed
buers)
File input/output
File Input/Output
Some of the available functions
Management
Assuming fp points to an open file
fflush(fp) flushes the buer of the associated stream.
rewind(fp) sets the file position indicator at the beginning of the
file.
Notes about the file position indicator:
indicates you current position within the file
with every read operation, it moves closer to the end of file
at the end of file, it takes the value EOF (check using feof(fp))
use rewind at this point (or earlier), to be able to reread your file
File input/output
File Input/Output
Some of the available functions
Output (writing)
fprintf prints a formatted string to an arbitrary stream.
fputs prints an unformatted string to an arbitrary stream.
fwrite is used primarily for writing data to binary files (well ignore it)
Input (reading)
fscanf reads formatted data from an arbitrary stream.
fgets reads an unformatted string from an arbitrary stream,
avoiding overflows (safer than gets)
fread is used primarily for reading data from binary files (well ignore
it)
File input/output
Using fprintf()
For example:
Do fprintf(stdout, This is arg1: %f, arg2: %e and arg3: %g\n, 3.14, 3.14, 3.14), or
printf(This is arg1: %f, arg2: %e and arg3: %g\n, 3.14, 3.14, 3.14)
File input/output
Using sprintf()
For example:
Do sprintf(str, This is arg1: %f, arg2: %e and arg3: %g\n, 3.14, 3.14, 3.14),
followed by printf(%s\n, str)
Do you need the newline character in printf? No, porque ya
est en la cadena
str
File input/output
Using fscanf()
int fscanf(FILE *stream, char *format, *arg1, ...);
Reads data from stream according to format and stores them in the
locations pointed to by the pointers argi
Whitespace characters are ignored
Often format consists purely of format specifiers, such as %d for
ints and %f for floats.
The return value indicates the number of successfully parsed items.
Not very user-friendly for reading strings (use fgets, instead).
For example:
Do fscanf(stdin, %d %f %c,&arg1, &arg2, &arg3), where arg1, arg2 and
arg3 are previously defined integer, float and character variables.
The same as scanf(%d %f %c, &arg1, &arg2, &arg3)
Using sscanf()
int sscanf(char *str, char *format, *arg1, ...);
This the same as fscanf, but instead of reading data from a stream,
we read from input string str.
For example:
char *str = "I love Julian , 3.14 and Dimitris";
char name1[10], name2[10];
float pi;
sscanf(str, "%*s %*s %s %*s %f %*s %s", name1, &pi, name2);
fprintf(stdout, "%s %s %f", name1, name2, pi);
Unformatted I/O
Writing Files
Some subtleties
Writing Files
Some subtleties
FILE *fp;
fp = fopen("myfile.txt", "w");
fclose(fp); // now "myfile.txt" is an empty file
File input/output
Writing Files
Some subtleties
FILE *fp;
fp = fopen("myfile.txt", "w");
fclose(fp); // now "myfile.txt" is an empty file
remove("myfile.txt"); // deletes the file
File input/output
Writing Files
Some subtleties
FILE *fp;
fp = fopen("myfile.txt", "r");
{check whether fp is NULL and act accordingly}
fclose(fp);
File input/output
File Input/Output
An overview
Start
Open
Golden Rules
Succeeded?
no
report
1 Test if opening your files was successful
yes
(NULL)
read/write 2 Test for terminating conditions (e.g.
EOF)
no
Done? 3 Do not forget to close your files once
yes
done!
close
End
Managing Large Programs
Outline
1 File input/output
Part C of CW4
Here you will need to use numbers.cpp and numbers.h. Since you use
these files as is, you only need to include the header file (without further
explanation).
Managing Large Programs Using Header Files
/* main.cpp */
#include <stdio.h>
#include <stdlib.h>
/* function declarations */
int myfcn1(char *str);
void myfcn2(int var);
/* main function*/
int main (void)
{
/* use myfcn1 and myfcn2, here */
}
/* function definitions */
int myfcn1(char *str)
{
/* stuff goes here */
}
/* myfunctions.h */
#include <stdlib.h>
#include <stdio.h>
/* main */ /* myfunctions.cpp */
int main (void) #include "myfunctions.h"
{
/* use myfcn1 and myfcn2, here */ int myfcn1(char *str)
} {
/* stuff goes here */
}
/* main.cpp */
#include <stdio.h>
#include <stdlib.h>
#include "numbers.h"
/* main function*/
int main (void)
{
/* use luhncheck() here */
}
/* numbers.h */
#include <stdio.h>
#include <stdlib.h>
#include "numbers.h"
return checksum;
}