45
Introduction to C Introduction to C Lecture 8: Lecture 8: Input / Output Input / Output Operating System Operating System

Introduction to C Lecture 8: Input / Output Operating System

Embed Size (px)

Citation preview

Page 1: Introduction to C Lecture 8: Input / Output Operating System

Introduction to CIntroduction to C

Lecture 8: Lecture 8:

Input / OutputInput / Output

Operating SystemOperating System

Introduction to CIntroduction to C

Lecture 8: Lecture 8:

Input / OutputInput / Output

Operating SystemOperating System

Page 2: Introduction to C Lecture 8: Input / Output Operating System

Computer Programming Concepts• Sequence

– บน ลง ล�าง , ซ้าย ไป ขาว• Conditions

– If, if else, if else if, switch• Iterations

– For (statement ; statement ; statement)

– While ( statement) do– Do While (statement)

Page 3: Introduction to C Lecture 8: Input / Output Operating System

Programming Concepts• First, make your program works. • Then make it pretty.• โปรแกรมคอมพิ�วเตอร� ความถู�กตองจะตองมา

ก�อนความสวยงาม• แต�โปรแกรมตองสวยงาม

Page 4: Introduction to C Lecture 8: Input / Output Operating System

Review

• Arrays– What is an array?– Array declarations– Array Initializations– Array Accessing

Page 5: Introduction to C Lecture 8: Input / Output Operating System

Review• String Functions

– Length?– Manipulation?– Comparison?– Searching?– What’s required?

Page 6: Introduction to C Lecture 8: Input / Output Operating System

Review• Functions

– What is function?– Why we use function?– How many type of parameter

passing?– What are they different?

Page 7: Introduction to C Lecture 8: Input / Output Operating System

Files in C

You do not need to know details of this structure: after assigning a pointer to a file structure, it is used for opening the file, reading from it or writing to it, and finally closing it.

Information about the file and its state:

• Location of the file on the disk• Type of the file• Allowed operations• Present position in the file

This information is kept lumped together in a structure. This structure has the generic name FILE, and it is defined in the header file stdio.h.

FILE *ifp, *ofp; /* pointers for input and output file */

Page 8: Introduction to C Lecture 8: Input / Output Operating System

Example: File i/o

#include <stdio.h> int main(void){

int a, sum = 0;FILE *ifp, *ofp /* input file pointer,

output file pointer */ 

ifp = fopen(“my_file”, “r”); /* open for reading */ofp = fopen(“outfile”, “w”); /* open for writing */.....

 fclose(ifp);fclose(ofp);

 The modes for opening files

Standard method for opening and closing files in C:

Pointers to structure

ifp = fopen("input.dat", "r"); if( ifp == NULL) { printf("can't open file\n");

return 1; }

It is good pratice to test if file was opened sucessfully:

Page 9: Introduction to C Lecture 8: Input / Output Operating System

File modes for fopen

MODE USED FOR FILE CREATED? EXISTING FILE?

"a" Appending Yes Appended to

"a+" Reading and appending

Yes Appended to

"r" Read only NoIf not found fopen returns NULL

"r+" Reading and writing NoIf not found fopen returns NULL

"w" Write only Yes Overwritten

"w+" Reading and writing Yes Overwritten

FILE *ifp; ifp = fopen(“filename”, “r”);

MS-DOS and MS-Windows have different modes for writing binary files: "ab“, “rb“, “wb“, "ab+“, “rb+“, “wb+“

Page 10: Introduction to C Lecture 8: Input / Output Operating System

To write to files: function fprintf() analogous to printf() To read from files: function fscanf() analogous to scanf()

fprintf(), fscanf()

printf() and scanf() are special cases of file i/o:

printf() is equivalent to fprintf(stdout, ....) scanf() is equivalent to fscanf(stdin, ....)

example: “%s %12.2f\n”

fprintf(ifp, control_string, other_args);fscanf (ifp, control_string, other_args);

In the file i/o functions, a file pointer has to be specified.

three predefined special file pointers:

stdin points to: keyboardstdout points to: screenstderr points to: screen

Page 11: Introduction to C Lecture 8: Input / Output Operating System

getc(), putc()To write character to file: putc(c,ofp) analogous to putchar(c) To read character from file: getc(ifp) analogous to getchar()

int c; c = getc(ifp);

EOF (end-of-file) character is not in the usual ASCII character set (0-255),

Use int instead of char if EOF is to be readputc(c, ofp);

#define getchar() getc(stdin)#define putchar(c) putc((c), stdout)

getchar() and putchar(c) are defined as macros:

Page 12: Introduction to C Lecture 8: Input / Output Operating System

ฟั!งก�ชั#น sprintf() และ sscanf()

• ฟั!งก�ชั#น sprintf() และ sscanf() เป$นฟั!งก�ชั#นส%าหร#บขอม�ลชัน�ดสายอ#กขระของ printf() และ scanf()

int sprintf(char *s, const char *format, …);int sscanf(const char *s, const char *format,

…);

Page 13: Introduction to C Lecture 8: Input / Output Operating System

ต#วอย�าง

char str1[]=“1 2 3 go”, str2[100], tmp[100];

int a,b,c;…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);Sprintf(str2,”DSC%d.jpg”,i);If (i==999) i=1;

Page 14: Introduction to C Lecture 8: Input / Output Operating System

Reading From a File• Steps

– Declare FILE variable– Open the file (read mode)– Read from the file– Close the file

Page 15: Introduction to C Lecture 8: Input / Output Operating System

ฟั!งก�ชั#น fopen() และ fclose()• ในเชั�งนามธรรม แฟั*มขอม�ล ค+อ

“สายของอ#กขระ”

ด#งน#,น ตองม-ต#วด%าเน�นการจ#ดการเป.ด และ ป.ด

Page 16: Introduction to C Lecture 8: Input / Output Operating System

Declare File Variable• Format: FILE *name;

– FILE type defined in <stdio.h>– Variable must be a pointer– E.g., FILE *infileptr;

Page 17: Introduction to C Lecture 8: Input / Output Operating System

Open the File• Format: fptr = fopen(“file”,”r”);

– E.g, infileptr = fopen(“my_file”,”r”);• “my_file” – file name• “r” – specifies read mode

– fptr is always set to the beginning of the file

– Check for successful file open• if ((infileptr = fopen(“my_file”,”r”)) !=

NULL)

Page 18: Introduction to C Lecture 8: Input / Output Operating System

ต#วอย�าง#include <stdio.h>int main() {

int a, sum=0;FILE *ifp, *ofp;ifp = fopen(“Input.txt”,”r”);ofp = fopen(“output.txt”,”w”);…while (fscanf(ifp, “%d”, &a)==1 )

sum+=a;fprintf(ofp,”The sum is %d.\n”,sum);…fclose(ifp);fclose(ofp);

}

Page 19: Introduction to C Lecture 8: Input / Output Operating System

Read from the File• One character at a time

– Format: c = getc(ifp)• getc reads from file pointer (ifp) and

returns a character• Similar to getchar

– Example• while ((c = getc(ifp)) != EOF)

– Continues reading characters until it reaches the end of the file

– c = fgetc(ifp) does the same thing

Page 20: Introduction to C Lecture 8: Input / Output Operating System

Read from the File• Multiple characters at a time

– Format: fgets (str, len, ifp)• Reads at most len – 1 chars from file

pointer (ifp) and store into the char array pointed to by str

• If new line or end of file encountered, reading stops

• Null char added to end of array• Example

– char line[100], *s;– while (fgets(s, 100, ifp) != EOF)

Page 21: Introduction to C Lecture 8: Input / Output Operating System

Read from the File• Structured input

– Format: fscanf(fptr,”cntrl”, args)• Reads from file pointed to by file pointer

(fptr)• Uses control string just like scanf• Args must be pointers• Example

– while (fscanf(ifp, “%d %s\n”, &num, str) != EOF)

» Reads an integer, string and new line from each line of the file pointed to by infileptr

Page 22: Introduction to C Lecture 8: Input / Output Operating System

Close the File• Format: fclose(fptr);

– Does everything to break the file connection

Page 23: Introduction to C Lecture 8: Input / Output Operating System

File Reading Example• Sum the numbers in a file

#include <stdio.h>void main () {

int num, sum = 0;FILE *inptr;

if ((inptr = fopen(“infile”, “r”)) != NULL) {while(fscanf(inptr, “%d”, &num) != EOF)

sum += num;fclose(inptr);printf(“The sum of the numbers is %d\

n”,sum);}

}

Page 24: Introduction to C Lecture 8: Input / Output Operating System

Programming Exercise• Write a program that

– Reads a list of first and last names from the file phonebook • The first and last names are stored one

per line

– Prints each entry as last name, first name

Page 25: Introduction to C Lecture 8: Input / Output Operating System

Writing to a File• Steps

– Declare FILE variable• Same as before

– Open the file (write mode)– Write to the file– Close the file

• Same as before

Page 26: Introduction to C Lecture 8: Input / Output Operating System

Open the File• Format: fptr = fopen(“file”,”w”);

– E.g, infileptr = fopen(“my_file”,”w”);• Creates new file

– Overwrites file if it exists

• Starts writing at the beginning of the file

– fopen(“file”, “a”) appends a file• Creates new file if it doesn’t exist

– Starts writing from the beginning

• Starts writing at the end of an existing file

Page 27: Introduction to C Lecture 8: Input / Output Operating System

Write to the File• One character at a time

– Format: putc(char, fptr)• putc writes a character to file pointer

(fptr) Similar to putchar

– Example• putc(‘\n’, outfileptr);

– Writes a newline to the file

– fputc(char, fptr) does the same thing

Page 28: Introduction to C Lecture 8: Input / Output Operating System

Write to the File• Multiple characters at a time

– Format: fputs (str, fptr)• Writes the null-terminated string to the

file• Does not write the null character• Example

– char s[6] = “Hello\0”;– fputs(s, outfileptr);

Page 29: Introduction to C Lecture 8: Input / Output Operating System

Write to the File• Structured output

– Format: fprintf(fptr,”cntrl”, args)• Writes to the file pointed to by file

pointer (fptr)• Uses control string just like printf• Example

– fprintf(outfileptr, “%d %s\n”, num, str);» Writes an integer and string to the file

Page 30: Introduction to C Lecture 8: Input / Output Operating System

File Writing Example• Write the sum of the numbers to a

file#include <stdio.h>void main () {

int num, sum = 0;FILE *inptr, *outptr;

if ((inptr = fopen(“infile”, “r”)) != NULL) {while(fscanf(inptr, “%d”, &num) != EOF)

sum += num;fclose(inptr);

if ((outptr = fopen(“outfile”, “w”)) != NULL) {fprintf(outptr,“The sum of the numbers is %d\

n”,sum);fclose(outptr);

}}

}

Page 31: Introduction to C Lecture 8: Input / Output Operating System

Programming Exercise• Write a program that

– Reads a list of first and last names from the file phonebook • The first and last names are stored one

per line

– Writes each entry as last name, first name to the file phonebook2• The entries are stored one per line

Page 32: Introduction to C Lecture 8: Input / Output Operating System

Moving around in files

rewind(file_ptr); resets the position indicator to start of file

ftell(file_ptr); returns the current value of file position indicator: i.e. no. of bytes from start of file

fseek(file_ptr, offset, place); moves file position indicator to specified position

When reading from or writing to a file, the system keeps track of thecurrent position in the file. Subsequent calls to fprintf() or fscanf() can then carry on where they left off, rather than starting again from the beginning.

However it is often useful to access a file at some random position instead.

The fseek function moves the indicator to offset bytes from place: place can be SEEK_SET, SEEK_CUR or SEEK_END (actually 0, 1 or 2) for beginning, current position or end of file espectively. Offset can be negative as well as positive.

Page 33: Introduction to C Lecture 8: Input / Output Operating System

Example of moving within a file

/* Write a file backwards */#include <stdio.h>#define MAXSTRING 100int main(void){

char fname[MAXSTRING];int c;

FILE *ifp;  fprintf(stdout, "\nInput a filename: "); scanf("%s", fname); ifp = fopen(fname, "r"); /* open for reading */ fseek(ifp, 0, SEEK_END); /* move to end of file */ fseek(ifp, -1, SEEK_CUR); /* back up one char */ while (ftell(ifp) > 0) { c = getc(ifp); /* move ahead one char */ putchar(c); fseek(ifp, -2, SEEK_CUR); /* back up 2 chars */ } return 0;} Notice we have to back up 2 chars, because

the act of reading in one char increments the file position indicator by 1.

Page 34: Introduction to C Lecture 8: Input / Output Operating System

Executing system commands

System commands are executed by use of the function system().

Example:

system(“date”);

passes the string “date” to the operating system, which executes it before returning control to the program.

The following code asks the system to write the directory to a temporary file, then reads it in from the temporary file and writes out to the screen in uppercase.

ls > junk.dat

writes a directory listing to the file junk.dat, (using the redirection operator > )

UNIX example:

Page 35: Introduction to C Lecture 8: Input / Output Operating System

#include <ctype.h>#include <stdio.h>#include <stdlib.h>int main(void){ int c; char command_string[100], *tmp_filename;

FILE *ifp;

  tmp_filename = tmpnam(NULL); sprintf(command_string, "ls > %s", tmp_filename); system(command_string); ifp = fopen(tmp_filename, "r");while ((c = getc(ifp)) != EOF)

putchar(toupper(c));remove(tmp_filename); return 0;

}

Example

equivalent to “ls > temp.dat”

delete the temporary file

Integer, not char, to read EOF-character

hard-coded string length limitunlikely to be exceeded!

The function tmpnam(NULL) returns a name for a temporary file (that doesn’t exist already), e.g. temp.dat

read from file one character at a time, convert to uppercase and put out to the screen

writes into the string command_string

command string “ls > temp.dat” is

sent to the system

open the temporary file for reading directory information from it

Page 36: Introduction to C Lecture 8: Input / Output Operating System

#include <ctype.h>#include <stdio.h>

int main(void){ int c; FILE *ifp;  ifp = popen("ls", "r"); /* open pipe */ while ((c = getc(ifp)) != EOF) putchar(toupper(c)); pclose(ifp); return 0;}

PipesIn Unix, you can use “pipes” to communicate directly with the operating system; this avoids the need for the temporary file in the previous example.

Example: uppercase2.c

... only for reading ...

... and ask it to send a directory listing

read from the pipe one character at a time, convert to uppercase and put out to the screen

... and close the pipe

Open a pipe to the operating system...

Page 37: Introduction to C Lecture 8: Input / Output Operating System

Arguments to main( )

/* Echoing command line arguments */#include <stdio.h>int main(int argc, char *argv[]) { int i; printf("argc = %d\n", argc); for (i = 0; i < argc; ++i) printf("argv[%d] = %s\n", i, argv[i]); return 0;}

Two arguments, conventionally called argc and argv, can be used with main() to communicate with the operating system.

argc counts the arguments (including the program name itself),

argv[] is an array of strings corresponding to the arguments.

Example: echoinput.c

Filenames are often passed in this way.

echoinput file1 file2

then argc will be 3;

argv[0] will be echoinput

argv[1] will be file1

argv[2] will be file2

argv[] are the arguments

argc is the number of arguments

Page 38: Introduction to C Lecture 8: Input / Output Operating System

Numeric arguments

#include <stdio.h>int main(int argc, char *argv[]) { int i; double x; i = atoi(argv[1]); x = atof(argv[2]); printf(“Input = %d, %lf\n",i,x); return 0;}

Only strings can be passed via the command line.In order to get numeric input, they must be converted to numers:

atoi() for converting a string to an integeratof() for converting a string to a double

Call with: ./program 123 4.567./program 123 4.567

Page 39: Introduction to C Lecture 8: Input / Output Operating System

The C compilercc [filename.c]

 Options include: -o [output file name]-lm to include the maths library-E to get output from preprocessor only (no compilation).

The compiler works in three stages: it preprocesses (replacing the #include, #define etc); it compiles; it links all of the pieces of code together into the executable program.

For a large program you can compile a small piece at a time, and link it to larger, pre-compiled parts. To compile only, use:

cc -c [filename.c]This creates object files (whose names end in .o), which can then be linked later

Page 40: Introduction to C Lecture 8: Input / Output Operating System

To do this with a set of .o files,

ar ruv g_lib.a gfopen.o gfclose.o gcalloc.o.......

This makes a library file called g_lib.a.

C Compiler: Libraries

To make the functions available to other programs, add the library tothe list of compiled files:

cc -o pgm main.c file1.c g_lib.a 

Follow this by

ranlib g_lib.a

which organises the file in a form that is useful for the linker.

It is possible to create libraries, which are (generally large) collections of useful object code ready for linking, so they don’t need to be compiled over and over again for different programs.

ar = archive ruv = replace, update, verbose

g_lib.a = output archive file nameobject files to go in the library

Page 41: Introduction to C Lecture 8: Input / Output Operating System

Conditional compilation

There is also an #ifndef, which includes lines if a name is not defined. There is also an #undef function to remove previous definitions, in order to prevent clashes.To match the #if, there is an #else; there is also #elif, which is short for else if.

The preprocessor can be used to exclude code from compilation:

#define DEBUG 1 /*set debug to true at top of file*/......#if DEBUG

printf(“debug: a = %d\n”, a);#endif

Because DEBUG has value 1, the printf statements will be compiled. The statements can be turned off by setting DEBUG = 0 at the start.

An alternative is #ifdef DEBUG

....#endifwhich will include the lines if DEBUG is defined at all at the top.

Page 42: Introduction to C Lecture 8: Input / Output Operating System

Preprocessor macros with arguments

#define SQ(x) ((x) * (x))

will replace, e.g., SQ(a + b) by ((a + b) * (a + b)) . Note here that all of the parentheses are needed!

Warning:Debugging code that contains macros with arguments can be very difficult!

#define min(x, y) (((x) < (y)) ? (x) : (y))

will replace an expression such asm = min(u, v)bym = (((u) < (v)) ? (u) : (v))The arguments of m can be arbitrary expressions of comparable type.  

Page 43: Introduction to C Lecture 8: Input / Output Operating System

Writing large programsA large program will normally be stored as a collection of .h and .c files in its own directory. If we are developing a program called pgm, we make a header file pgm.h, which contains #includes, #defines and a list of function prototypes.

All .c files should then have #include “pgm.h”

at the top. Note the use of quotes rather than in < >, when you include your own header files. The compiler then looks in the current directory rather than in the directory for standard C header files.

Compile with the usual command, listing all of the .c files and libraries, but not the .h files, which are included automatically by the #include preprocessor commands.

Page 44: Introduction to C Lecture 8: Input / Output Operating System

Header files in large programs

Often the same header files are included in several different source code files. How to avoid multiple definitions when the header file is compiled repeatedly?

Let us assume we have a header file called MyHeaderFile1.h.:

#ifndef MYHEADERFILE1#define MYHEADERFILE1

.... function prototypes;

.... definitions;

#endif

Thus, the material in the file is only included if it hasn’t been included already.

this is only compiled ifMYHEADERFILE1 is not defined(i.e. if the header file has not been processed before)

Page 45: Introduction to C Lecture 8: Input / Output Operating System

End

• Strictly follow the C-syntax Strictly follow the C-syntax

• Don‘t forget to prototype all your functionsDon‘t forget to prototype all your functions

• Use indentation to get your bracketing right Use indentation to get your bracketing right

• Use parentheses to clarify operator precedenceUse parentheses to clarify operator precedence

• Use typecasting (double) in integer divisions Use typecasting (double) in integer divisions

• Use pointers to pass variables to functions Use pointers to pass variables to functions