input / output and the os. declarations and initializations char c = ‘a’, s[] = “blue...
Post on 21-Dec-2015
214 views
TRANSCRIPT
Declarations and Initializations
char c = ‘A’, s[] = “Blue moon!”;
Format Printed Remarks
%c “A ” field width 1 by default
%2c “ A” field width 2, right adjusted
%-3c “A ” field width 3, left adjusted
%s “Blue moon!” field width 10 by default
%3s “Blue moon!” more space is needed
%.6s “Blue m” precision 6
%-11.8s “Blue moo ” precision 8, left adjusted
Declarations and Initializations
int i = 123;
double x = 0.123456789;
Format Printed Remarks
%d “123” field width 3 by default
%05d “00123” padded with zeros
%7o “ 173” right adjusted, octal
%-9x “7b ” left adjusted, hexadecimal
%-9#x “0x7b ” left adjusted, hexadecimal
%10.5f “ 0.12346” field width 10, precision 5
%-12.5e “1.23457e-01” left adjusted, e-format
Input and Output functionsfprintf(), fscanf(), sprintf(), sscanf()
stdin standard input file connected to the keyboard
stdout standard output file connected to the screen
stderr standard error file connected to the screen
int fprintf( FILE *fp, const char *format, ...);
int fscanf( FILE *fp, const char *format, ...);
fprintf( stdout, ... ); printf( ....);
fscanf( stdint, ...); scanf( .... );is equivalent tois equivalent to
sprintf and sscanf
int sprintf(char *s , const char *format, ...);
int sscanf(const char *s, const char *format, ...);
sprintf and sscanf
char str1[] = “1 2 3 go”, str2[100], tmp[100];
int a = 0, b = 0, c = 0;
sscanf( str1, “%d%d%d%s”, &a, &b, &c, tmp);
sprintf( str2, “%s %s %d %d %d\n”, tmp, tmp, a, b, c);
printf( “%s”, str2 );
output:
go go 1 2 3
scan from the string into the variables
scan from the string into the variables
print into the stringprint into the string
print the string to the screenprint the string to the screen
Working with Files#include <stdio.h>
int main( void )
{
int a = 0, sum = 0;
FILE *ifp = NULL, *ofp = NULL;
ifp = fopen( “my_file”, “r” );
ofp = fopen( “outfile”, “w”);
.....
while ( fscanf( ifp, “%d”, &a ) == 1 )
sum += a;
fprintf( ofp, “The sum is %d. \n”, sum );
....
fclose( ifp );
fclose( ofp );
}
file pointersfile pointers
open the files for reading / writing
open the files for reading / writing
close the filesclose the files
Double Spacing a File#include <stdio.h>
#include <stdlib.h>
void double_space( FILE *, FILE * );
void prn_info( char * );
void prn_err_msg( char * );
int main( int argc, char **argv )
{
int rtVal = 0;
FILE *ifp, *ofp;
if ( argc == 3 )
{
make sure that we got all the input parameters
make sure that we got all the input parameters
the return valuethe return value
Double Spacing a File
ifp = fopen( argv[1], “r” );
if ( ifp != NULL )
{
ofp = fopen( argv[2], “w” );
if ( ofp != NULL )
{
double_space(ifp, ofp);
fclose(ofp);
}
else rtVal = 3;
fclose(ifp);
}
else rtVal = 2;
}
make sure the input file is openmake sure the input file is open
make sure the output file is openmake sure the output file is open
mark the error type (which file did not open ... )
mark the error type (which file did not open ... )
Double Spacing a File
else
{
rtVal = 1;
prn_info( argv[0] );
}
if ( rtVal > 1 )
prn_err_msg( argv[ 2 ] );
return rtVal;
}
the else of ( argc == 3 )the else of ( argc == 3 )
file not open error messagefile not open error message
Double Spacing a File
void prn_info( char *pgm_name )
{
printf( “\n%s%s%s\n\n%s%s\n\n”,
“Usage: ”, pgm_name, “ infile outfile”,
“The contents of infile will be double-spaced ”,
“and written to outfile.” );
}
void prn_err_msg( char *file_name )
{
printf( “\n%s%s\n\n”, “Error – could not open file ”, file_name );
}
Double Spacing a File
void double_space( FILE *ifp, FILE *ofp )
{
int c = 0;
while ( ( c = getc( ifp ) ) != EOF )
{
putc( c, ofp );
if ( c == ‘\n’ )
putc( ‘\n’ , ofp );
}
}
found a new line, duplicate itfound a new line, duplicate it
Replicating a File with Caps#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
FILE* gfopen( char* file_name, char* mode);
int main( int argc, char **argv )
{
int c = 0;
FILE *fp = NULL, *tmp_fp = NULL;
if ( argc != 2 )
{
fprintf(stderr, “\n%s%s%s\n\n%s\n\n”, “Usage: ”, argv[0], “ file_name”,
“The file will be doubled and some letters capitalized.” );
exit(1);
}
fp = gfopen( argv[1], “r+” );
tmp_fp = tmpfile();
while ( ( c = getc( fp ) ) != EOF )
putc( toupper( c ), tmp_fp );
rewind( tmp_fp );
fprintf( fp, “---\n” );
while ( ( c = getc( tmp_fp ) ) != EOF )
putc( c, fp );
return 0;
}
Replicating a File with Caps
Replicating a File with Caps
FILE* gfopen( char* file_name, char* mode )
{
FILE *fp = NULL;
if ( ( fp = fopen( file_name, mode ) ) == NULL )
{
fprintf( stderr, “Cannot open %s - bye!\n”, file_name );
exit(1);
}
return fp;
}
not always the best idea, this could leave behind allocated
memory and open files ... but you get the general idea
not always the best idea, this could leave behind allocated
memory and open files ... but you get the general idea
Results
in file apple: A is for apple and alphabet pie.
command: replicate_with_caps apple
output:
A is for apple and alphabet pie
---
A IS FOR APPLE AND ALPHABET PIE
fseek
fseek(file_ptr, offset, place);
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
ftell(file_ptr);
beginning of the filebeginning of the file
current position in the filecurrent position in the file
end of the fileend of the file
Write a File Backwards
#include <stdio.h>
#define MAXSTRING 100
int main( void )
{
char file_name[MAXSTRING] = { 0 };
int c = 0;
FILE *ifp = NULL;
fprintf( stderr, “\nInput a file name: ” );
scanf( “%s”, file_name );
ifp = fopen( file_name, “rb” ); binary mode for ms-dosbinary mode for ms-dos
Write a File Backwards
fseek( ifp, 0, SEEK_END );
fseek( ifp, -1, SEEK_CUR );
while ( ftell( ifp ) >= 0 )
{
c = getc( ifp );
putchar( c );
fseek( ifp, -2, 1 );
}
return 0;
}
move to the end of the filemove to the end of the file
back up one characterback up one character
move ahead one charactermove ahead one character
back up two charactersback up two characters
Change the Case of Letters in a File
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFSIZE 1024
int main(int argc, char **argv)
{
char mybuf[BUFSIZE] = { 0 }, *p = NULL;
int in_fd = 0, out_fd = 0, n = 0;
in_fd = open( argv[1], O_RDONLY );
out_fd = open( argv[2], O_WRONLY | O_EXCL | O_CREAT, 0600 );
use io.h in ms-dosuse io.h in ms-dos
open fileopen file
file permissionsfile permissions
Change the Case of Letters in a File
while ( ( n = read( in_fd, mybuf, BUFSIZE ) ) > 0 )
{
for ( p = mybuf; p - mybuf < n; ++p )
{
if ( islower( *p ) ) *p = toupper(*p);
else if ( isupper( *p ) ) *p = tolower(*p);
}
write( out_fd, mybuf, n );
}
close( in_fd );
close( out_fd );
return 0;
}
write and close filewrite and close file
File Permissionsr-- 100 04-w- 010 02--x 001 01rw- 110 06r-x 101 05-wx 011 03rwx 111 07
++++++
rw------- 0600rw----r-- 0604rwxr-xr-x 0755rwxrwxrwx 0777
File Open Flag Options
O_CREAT
O_EXCL
O_NOCTTY
O_TRUNC
O_APPEND
O_NONBLOCK
O_NDELAY
O_SYNC
O_NOFOLLOW
O_DIRECTORY
O_LARGEFILE
Direct Input / Output
int fread(void *a_ptr, int el_size, int n, FILE *fp);
int fwrite(void *a_ptr, int el_size, int n, FILE *fp);
used to read and write binary files, no conversions are performedused to read and write binary files, no conversions are performed
Change the Case of Letters in a File
#include <ctype.h>
#include <stdio.h>
#define BUFSIZE 1024
int main(int argc, char **argv)
{
char mybuf[BUFSIZE] = { 0 }, *p = NULL;
FILE *ifd = NULL, *ofd = NULL;
int n = 0;
ifp = fopen( argv[1], “r” );
ofp = fopen( argv[2], “w” );
open the file for readingopen the file for reading
open the file for writingopen the file for writing
Change the Case of Letters in a File
while ( ( n = fread( ifd, mybuf, BUFSIZE ) ) > 0 )
{
for ( p = mybuf; p - mybuf < n; ++p )
{
if (islower(*p)) *p = toupper(*p);
else if (isupper(*p)) *p = tolower(*p);
}
fwrite(ofd, mybuf, n);
}
fclose(ifd);
fclose(ofd);
return 0;
}
read from the fileread from the file
write to the filewrite to the file
close the filesclose the files
Write only Lowercase on Screen
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXSTRING 100
int main( void )
{
char command[MAXSTRING] = { 0 }, *tmp_filename = NULL;
int c = 0;
FILE *ifp = NULL;
tmp_filename = tmpnam( NULL );
sprintf( command, “dir > %s”, tmp_filename );
create a temporary file namecreate a temporary file name
Write only Lowercase on Screen
system( command );
ifp = fopen( tmp_filename, “r” );
while ( ( c = getc( ifp ) ) != EOF )
putchar( tolower( c ) );
remove( tmp_filename );
return 0;
}
execute the system commandexecute the system command
remove the temporary fileremove the temporary file
#include <ctype.h>
#include <stdio.h>
int main( void )
{
int c = 0;
FILE *ifp = NULL;
ifp = popen( “ls”, “r” );
while ( ( c = getc( ifp ) ) != EOF )
putchar( toupper( c ) );
pclose( ifp );
return 0;
}
Profiling
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 50000
void quicksort(int *, int *);
int main(void)
{
int a[N] = { 0 }, i = 0;
srand( time( NULL ) );
for ( i = 0; i < N; ++i )
a[i] = rand() % 10000;
seed the random functionseed the random function
create a number between 0 and 9999create a number between 0 and 9999
Profiling
quicksort( a, a + N – 1 );
for ( i = 0; i < N - 1; ++i )
{
if ( a[i] > a[i + 1] )
{
printf( “SORTING ERROR - bye!\n” );
exit( 1 );
}
}
return 0;
}
Profiling
cc -p -o quicksort main.c quicksort.c
quicksort→mon.out
prof quicksort
% time cumsecs #call ms / callname func name
46.9 7.18 9931 0.72 _partition
12.1 9.64 1 2460.83 _main
11.7 11.43 19863 0.09 _find_pivot
… … … … …
0.0 15.33 1 0.0 _time
Timing Functions
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
clock_t clock(void);
#define CLOCKS_PER_SEC 60
time_t time(time_t *p);
double difftime(time_t, time_t);
time used by the machinetime used by the machine
machine dependentmachine dependent
seconds since 1970seconds since 1970
Timing Functions#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXSTRING 100
typedef struct
{
clock_t begin_clock, save_clock;
time_t begin_time, save_time;
} time_keeper;
static time_keeper tk;
void start_time(void)
{
tk.begin_clock = tk.save_clock = clock();
tk.begin_time = tk.save_time = time(NULL);
}
known only to this fileknown only to this file
Timing Functions
double prn_time(void)
{
char s1[MAXSTRING] = { 0 }, s2[MAXSTRING] = { 0 };
int field_width = 0, n1 = 0, n2 = 0;
double clocks_per_second = (double) CLOCKS_PER_SEC,
user_time = 0, real_time = 0;
user_time = ( clock() - tk.save_clock ) / CLOCKS_PER_SEC;
real_time = difftime( time( NULL ), tk.save_time );
tk.save_clock = clock();
tk.save_time = time(NULL);
Timing Functions
n1 = sprintf( s1, “%.2f”, user_time );
n2 = sprintf( s2, “%.2f”, real_time );
printf( “ s1=%s n1=%d\n”, s1, n1 );
printf( “ s2=%s n2=%d\n”, s2, n2 );
field_width = ( n1 > n2 ) ? n1 : n2;
printf( “%s%*.2f%s\n%s%*.2f%s\n\n”,
“User time: ”, field_width, user_time, “ seconds”,
“Real time: ”, field_width, real_time, “ seconds” );
return user_time;
}
print the values found, and do it neatly
print the values found, and do it neatly
Compare float and double multiplication times
#include <stdio.h>
#include "u_lib.h"
#define N 100000000
int main(void)
{
long i = 0;
float a = 0, b = 3.333, c = 5.555;
double x = 0, y = 3.333, z = 5.555;
printf( “Number of multiplies: %d\n\n”, N );
printf( “Type float:\n\n” );
one hundred millionone hundred million
arbitrary valuesarbitrary values
Compare float and double multiplication times
start_time();
for ( i = 0; i < N; ++i )
a = b * c;
prn_time();
printf( “Type double:\n\n” );
for ( i = 0; i < N; ++i )
x = y * z;
prn_time();
return 0;
}
Compare float and double multiplication times
Number of multiplies: 100000000
Type float:
User time: 33.6 seconds
Real time: 34.0 seconds
Type double:
User time: 33.5 seconds
Real time: 33.0 seconds
#include <stdio.h>
int main( int argc, char *argv[], char *env[] )
{
int i = 0;
for ( i=0; env[i] != NULL; ++i )
printf( “%s\n”, env[i] );
return 0;
}