Monday, December 12, 2011

Basic on C


I/O in C
• Built in statements/functions for input and
output.
• I/O library functions are listed in the header
file: stdio.h.



Streams
• All input and output is performed with
“streams”.
• A ‘stream” is a sequence of characters
organised into a line.
• Each line consists of zero or more characters
and ends with the “newline” character.



Types of 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.
• Input and output file streams for reading from
and writing to files.



printf()
• This function provided for formatted output to
the screen.
• The syntax is:
– printf( format, var1, var2, ... );
• The format includes a listing of the data types
of the variables to be output and, optionally,
some text and control characters.


Data Format
• d - displays a decimal (base 10) integer.
• l – used with other specifiers to indicate a “long”.
• f – displays a floating point value.
• e – displays a floating point value in exponential
notation.
• g – displays a number in either “e” or “f” format.
• c – displays a single character.
• s – displays a string of characters.


Flags
• “-” - left justify the value.
• “+” - precede value with a “+” or “-”
• “ ” (space) – precede positive value with a space.
• “0” – zero fill numbers.
• “#” – precede octal value with “0”, hexadecimal value
with a “0x”, display decimal point for floats, leave
trailing “0”s for “g” or “G” format.
You do not need to memorise them, just be
familiar with them.


Width and Precision
• “*” – take next argument to printf as size of field:
*d -> %10d (10 spaces maximum for an integer).
• “.*” – take next argument to printf as precision:
*.*f -> %13.2f (13 spaces maximum with 2 decimal places).
• Also:
– Number of digits to display for integers,
– Number of decimal places for “e” as well as “f” formats.
– Maximum number of significant digits to display for “g”.
– Maximum number of characters for “s” format.


scanf()
• This function provides for formatted input
from the keyboard.
• The syntax is:
– scanf ( format , &var1, &var2, ... );
• The format is a listing of the data types of the
variables to be input and the & in front of
each variable name tells the system where to
store the value that is input. It provides the
address for the variable (remember passing
by reference from two weeks ago?).




getchar()
• This function provides for getting exactly one
character from the standard input (keyboard).
• Example:
char ch;
ch = getchar();




putchar()
• This function provides for printing exactly one
character to the screen.
• Example:
char ch;
ch = getchar(); /* input a character */
putchar ( ch ); /* display it to the screen */



File Input and Output
• Read from a file on disk.
• Write to a file on disk.
• Benefits:
– Data read from a file instead of typing them in.
– Storage capabilities.
– Cost.
• Note files can be anywhere and of any type:
– Local disk.
– Remote disk (other computer).
– Audio input and output.
– Video input and output.



Dealing with Files in C
• A file is simply a sequential stream of bytes.
• C imposes no structure on a file – user needs to
know structure.
• Must be “opened” before it can be accessed for
reading or writing.
• Successfully opening a file returns a “pointer” to a file
“structure” defined as a FILE.
• Consider the statement that declares two pointer
variables of type FILE:
FILE *fptr1, *fptr2;





Buffered Input and Output
• Computationally expensive to read/write a byte
at a time.
• Read/write large blocks of data into a “buffer” –
assumes bytes close together on disk related.
• May affect the running of your program.






Opening Files
• The statement:
fptr1 = fopen ( “mydata”, ”r”);
opens the file “mydata” for input (reading).
• The statement:
fptr2 = fopen ( “results”, ”w”);
opens the file “results” for output (writing).
• Once the files are open, they stay open until
you close them or exit the program.
• Exiting the program will close all files.



Testing for Successful Opening
• If file was not able to be opened, the value
returned by fopen is NULL.
• Example: assume the file “mydata” does not
exist. Then:
FILE *fptr1;
fptr1 = fopen ( “mydata.txt”, “r” );
if (fptr1 == NULL )
{
printf(“File mydata.txt did not open\n”);
}





Reading From Files
• Use of fscanf instead of scanf:
int a, b;
FILE *fptr1;
fptr1 = fopen ( “mydata.txt”, “r”)
if (fptr1 == NULL )
{
printf(“File mydata.txt did not open\n”);
}
else{
fscanf(fptr1, “%d%d”, &a, &b);
printf(“a = %d, b = %d\n”,a,b);
}
• The fscanf function reads values from the
file “pointed” to by fptr1, and assign those
values to a and b.


Reading From Files – more example
• Read multiple data in the same file
int i;
int number, a, b;
FILE *fptr1;
fptr1 = fopen ( “mydata2.txt”, “r”);
fscanf(fptr1, “%d”, &number);
for(i=1;i<=number;i++){
fscanf(fptr1, “%d %d”, &a, &b);
printf(“%d %d\n”, a, b);
}
fclose(fptr1); /* see later slides */




End of File
• The end-of-file indicator informs the program
when there are no more data (no more bytes)
to be processed or read.
• Numerous ways to test for the end-of-file
condition:
– Value returned by the function feof().
– Value returned by fscanf().



End-of-file Testing Methods
• Use of feof():
fscanf ( fptr1, “%d”, &var);
if ( feof (fptr1) )
{
printf(“End-of-file encountered\n”);
}
• Use of fscanf():
int istatus;
istatus = fscanf ( fptr1, “%d”, &var);
if ( istatus == EOF ) //istatus = -1 if EOF
{
printf(“End-of-file encountered\n”);
}



Reading From Files – more example
• Read multiple data in the same file without total number to read

int i;
int number, a, b;
int istatus;
FILE *fptr1;
fptr1=fopen("mydata3.txt","r");
do
{
istatus = fscanf(fptr1,"%d %d", &a, &b);
if (istatus==EOF)
printf("End-of-File Encountered\n");
else
printf("%d %d\n", a, b);
}
while (istatus!=EOF);
fclose(fptr1);


Writing to Files
• Example:
int a = 5, b = 20;
FILE *fptr2;
fptr2 = fopen ( “results.txt”, “w”);
fprintf ( fptr2, “%d %d\n”, a, b);
fclose(fptr2); /* see next slide */


putc()
• This function is similar to putchar() except
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, fptr2 ); /* output to a file */

Writing To and Reading From Files


#include <stdio.h>
int main(void)
{
FILE *outfile, *infile;
int b = 5, f;
float a = 13.72, c = 6.68, e, g;
outfile = fopen ( “testdata.txt”, “w”);
fprintf ( outfile, “%6.2f %2d %5.2f”, a, b, c);
fclose ( outfile );
infile = fopen ( “testdata.txt”, “r”);
fscanf ( infile, “%f %d %f”, &e, &f, &g);
printf ( “%6.2f, %2d, %5.2f\n”, e, f, g);
fclose ( infile );
return 0;
} code10_6.c
create testdata.txt

Comparison of data
13.72 5 6.68 /* what’s in testdata file*/
13.72, 5, 6.68 /* what’s output to screen */

Generating a csv File
• You may need to read or write files in specific
formats.
• Popular example:
– Excel “csv” files.
– Comma delimited – data values separated by “,”.
– One line of data values per line of a table.
– One set of data value per column.
• Example:
• Write to a file, the data values for sine and cosine waves for
values ranging from 0 to 360 degrees (0 to 2π radians) in 10
degree steps.
• Three values per row:
• degrees, sine(degrees), cosine(degrees)
Solution – excel.c
#include <stdio.h>
#include <math.h>
#define PI 3.141592653
int main(void)
{
float degrees, sine, cosine;
float degrees_to_radians = PI / 180.0;
FILE *output;
int istatus;
output = fopen ("sine.csv", "w");
fprintf( output, "angle, sine, cosine \n");
for ( degrees = 0.0; degrees <= 360.0; degrees += 10.0)
{
sine = sin(degrees * degrees_to_radians);
cosine = cos(degrees * degrees_to_radians);
fprintf( output, "%f, %f, %f\n",degrees, sine, cosine);
}
fclose (output);
}


angle sine cosine
0 0 1
10 0.173648 0.984808
20 0.34202 0.939693
30 0.5 0.866025
40 0.642788 0.766044
50 0.766044 0.642788
60 0.866025 0.5
70 0.939693 0.34202
80 0.984808 0.173648
90 1 0
100 0.984808 -0.173648
110 0.939693 -0.34202
120 0.866025 -0.5
130 0.766044 -0.642788
140 0.642788 -0.766044
150 0.5 -0.866025
160 0.34202 -0.939693
170 0.173648 -0.984808
180 0 -1
190 -0.173648 -0.984808
200 -0.34202 -0.939693
210 -0.5 -0.866025
220 -0.642788 -0.766044
230 -0.766045 -0.642788
240 -0.866025 -0.5
250 -0.939693 -0.34202
260 -0.984808 -0.173648
270 -1 0
280 -0.984808 0.173648
290 -0.939693 0.34202
300 -0.866025 0.5
310 -0.766044 0.642788
320 -0.642788 0.766044
330 -0.5 0.866025
340 -0.34202 0.939693
350 -0.173648 0.984808
360 0 1


Today we discussed…


Input and output.
• Standard streams.
• Files.
• Generating csv files.













No comments:

Post a Comment