Topics C IO COMP 21000 John Barr Output printf 2 2 printf score dn score Input scanf 2 3 scanf d d ampexam1 ampexam2 File IO include lt ID: 757525
Download Presentation The PPT/PDF document "Introduction to Computer Organization &a..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Introduction to Computer Organization & Systems
Topics:C I/O
COMP 21000
John BarrSlide2
Output: printf
2-
2
printf(
“
score = %d\n
”,score);Slide3
Input: scanf
2-
3
scanf
(
“
%d %d
”
,&exam1, &exam2);Slide4
File I/O
#include <stdio.h>#include <stdlib.h
>#define SIZE 10int main(){
int
line[SIZE]; int n; FILE *fname;
/* verify that we can open the file */ if ( (fname = fopen("nums.txt", "r")) == NULL) { fprintf(stderr, "cannot open nums.txt for reading"); exit(1); } for (n = 0; n < 10; n++) { fscanf(fname, "%d", &line[n]);
printf("Entered %d\n", line[n]); } for (n = 0; n < 10; n++)
{ printf("n = %d \t line = %d\n", n, line[n]); } fclose(fname
); // always close a file! printf ("Goodbye! \n");
return 0;}
2-
4
Variable
fname
is a file pointer
Function
fopen
will open
the file given as the first
argument of the command line.
Function
fscanf
reads from the file indicated by its first argument.
fopen
reference: https://
www.tutorialspoint.com
/
c_standard_library
/
c_function_fopen.htm
See /home/
barr
/Student/comp210/examples/
readNum.c
See the online textbook “Dive into Systems”, chap 2.8Slide5
File I/O
#include <stdio.h>#include <stdlib.h>#define SIZE 10int
main(){ int line[SIZE]; int n; FILE *fname; /* verify that we can open the file */
if ( (
fname
= fopen("nums2.txt", "w")) == NULL) { fprintf(stderr, "cannot open nums.txt for writing"); exit(1); } printf
("Enter 10 numbers: "); // continued on next slide2-
5
Variable
fname
is a file pointer
Function
fopen
will open
the file given as the first
argument of the command line.
Continued on next slide
See /home/
barr
/Student/comp210/examples/
writeNum.cSlide6
File I/O
for (n = 0; n < 10; n++) { scanf("%d", &line[n]); printf("Entered %d\n", line[n]);
} for (n = 0; n < 10; n++) { fprintf(fname, "n = %d \t line = %d\n", n, line[n]); }
fclose
(
fname); printf ("Goodbye! \n"); return 0;}
2-6
Scanning from
stdin
Function
fprintf
writes to the file indicated by its first argument.
Always close any file that you use!Slide7
Command Line
int main(
int argc, char *argv[ ])
{
int j; if (argc != 2) {
printf("factorial takes one integer argument\n"); return(1); /* abnormal termination. */ } /* ASCII string to integer conversion; in stdlib.h */ j = atoi(argv[1]); printf("factorial(%d) = %d\n", j, factorial(j)); return(0);}
2-
7
Argc indicates the number of command line arguments (including the program name).
Argv is an array of pointers to char
(strings) that lists all of the command
line arguments.Slide8
Command Line
#include <stdio.h>#include <stdlib.h>
int factorial (
int
n)
{ int ans = 1; if (n < 0) n = -1 * n; while (n > 1)
{ ans *= n; n--; } return(ans);}
2-
8Slide9
File I/O
#include <stdio.h>#include <stdlib.h
>#define SIZE 100int main(int
argc
, char *argv[ ]){ char
line[SIZE]; int n; FILE *fname; if (argc <2) { fprintf(stderr, "%s : you must include a file name \n",argv[0]); exit(1); } /* verify that we can open the file */ if ( (fname
= fopen(argv[1], “w”)) == NULL)
{ fprintf(stderr, “%s: cannot open %s for writing”, argv[0], argv[1]); exit(1);
} printf(“Enter some lines. End your input with ^d: \n”);
while ( (n = readline(line, SIZE) ) > 0)
fprintf(fname, “n = %d \t line = %s\n”, n, line);
fclose(fname);
printf (“Goodbye! \n”);
}
2-
9
Variable
fname
is a file pointer
Function
fopen
will open
the file given as the first
argument of the command line.
Function
fprintf
writes to the file indicated by its first argument.
See /home/
barr
/Student/comp210/examples/
readNumCmd.cSlide10
File I/O
/* This function will read an entire line including white space until either a newline character of the EOF character is found */int readline
(char s[ ],int max){
int
c,i=0; max--; while (i < max && (c = getchar
()) != EOF && c != '\n') s[i++] =c; if (c == '\n') s[i++] = c; s[i] = '\0'; return(i);}
2-
10Slide11
File I/O: reading part 1#include <
stdlib.h>#include <stdio.h>#define ROW 5
#define COL 4int main(int argc, char *
argv
[])
{ int *line[5]; int n, i, *
ptr; FILE *fname; if (argc <2) { // if there is no command line argument, use a default name fname = fopen(”nums2D.txt", "r"); } else fname = fopen(argv[1], "r"); // error check; did the file open? if (fname
== NULL) { fprintf(stderr, "Could not open %s\n",
argv[1]); exit(1); }
2-
11
here’s where we open the file
fname
is the file descriptor variable
See /home/
barr
/Student/comp210/examples/read2D.c
Reading files using dynamic memorySlide12
File I/O: reading part 2 for (n = 0; n < ROW; n++)
line[n] = (int *)malloc(4*sizeof(int
)); for (n = 0; n < ROW; n++) { ptr = line[n];
for (
i
= 0; i < COL; i++) { fscanf(
fname, "%d", ptr++); } } printf( "The numbers are: \n"); for (n = 0; n < ROW; n++){ for (i = 0; i < COL; i++) { printf("%d ", line[n][i]); }
printf("\n"); }}
2-
12
here’s where we read in from the file
Dynamically allocate memorySlide13
Other IO functions
#include <stdio.h> int
fgetc(FILE *stream); char *fgets(char
*
s
, int size, FILE *stream);
int getc(FILE *stream); int getchar(void); char *gets(char *s); int ungetc(int c, FILE *stream);
2-
13Slide14
Other IO functions
int fgetc( std::FILE* stream ); reads the next character from stream and returns it as an unsigned
char cast to an int, or EOF on end of file or error. int getc( std::FILE* stream );
is equivalent to
fgetc()
except that it may be implemented as a macro which evaluates stream more than once. getchar() is equivalent to getc(stdin).
2-14Slide15
Other IO functions
char* gets( char* str ); reads a line from
stdin into the buffer pointed to by str until either a terminating newline or EOF, which it replaces with
'\0'
.
No check for buffer overrun is performed.char* fgets( char* str, int n, FILE* stream ); reads in at most one less than
n characters from stream and stores them into the buffer pointed to by str. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer. ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed - back characters will be returned in reverse order; only one pushback is guaranteed.
2-
15Slide16
Scanf problemsHow is white space handled?
scanf(“%d”, &x); User enters 25\nThe ‘\n’ may stay in the input streamSolutions:
scanf(“%d “, &x);
2-
16
Note the space after the ‘d’Slide17
Scanf problemsHow is white space handled?
scanf(“%d”, &name); User enters John BarrThe variable name now holds “John”Solutions:
printf("Enter a string\n");scanf("%[^\n]s", str1); __fpurge(stdin);
2-
17
Note the space after the ‘John’
char name[32]
Reads all char except ‘\n’ charBut will read the final ‘\n’ so must purgeSlide18
Scanf problemsA better way to read a string
fgets( char* str, int
n, stdin ); User enters John Barrfgets(str1, MAX, stdin);
if
((
strlen(str1) > 0) && (str1[strlen (str1) - 1] == '\n')) str1[strlen (str1) - 1] = '\0';
2-18
Reads up to MAX char or to the ‘\n’ charAlways puts a ‘\0’ at the end of the characters read.
Also reads the ‘\n’ charWe put a ‘\0’ in place of the ‘\n’ if necessarySlide19
Scanf problemsSolutions:
scanf(”%[^\n]", &name);Brackets []List the characters to match. Will only scan in matched characters.
If begin with a ^ then these are characters to ignore.If use a hyphen, matches all in between characters, e.g., [a-g]Input stops as soon as the first non-acceptable character is readNote that with brackets you don’t need a formatting character. Brackets are always read as a string.
2-
19
Reads all char up to the ‘\n’ char
i.e., says continue reading but don’t read the ‘\n’Slide20
Example#include <stdio.h
>int main(){ char name[32]; int x;
printf("Enter a name with spaces: "); scanf("%[^\n]", name); // notice that no 's' formatting char is necessary printf("\nname: %s\n", name);
// zero out the name
name[0] = '\0';
printf("Enter some characters: "); scanf("%*[\n]%[a-g]", name); // ignores the newline char printf("accepted characters: %s\n", name); scanf("%s", name);
printf("unaccepted characters: %s\n", name); // zero out the name name[0] = '\0'; printf("Now enter 3 characters: "); /* with a number, need either a formatting char or brackets to specify input characters */ scanf("%3s", name); printf("The 3 characters are: %s\n", name);}2-20See Student/Comp210/examples/testRead.ctestReadEnter a name with spaces: John Barr
name: John BarrEnter some characters: abchijdefaccepted characters: abcunaccepted characters:
hijdefNow enter 3 characters: mnopqThe 3 characters are: mnoSlide21
Scanf problems
scanf formatting string:% * maximum-field-width length Letter
2-
21
Conversion modifier
Description
ExampleInputResults
*Assignment Supression. This modifier causes the corresponding input to be matched and converted, but not assigned (no matching argument is needed).int
anInt;scanf("%*s %i", &anInt);Age:·29anInt==29,return value==1Max field width
This is the maximum number of character to read from the input. Any remaining input is left unread. int anInt; char s[10];scanf("%2i", &anInt);scanf("%9s", s);
2345VeryLongStringanInt==23,
return value==1s=="VeryLongS" return value==1
Length modifierThis specifies the exact type of the matching argument.double d;scanf
("%lf", &d);3.14d==3.14return value==1Slide22
Scanf problemsBuffer overflow?
scanf(“%d”, &name); User enters John BarrMajor source of exploitsSolutions:scanf(”%4[^\n]", &name);
2-
22
Overflows the allocated memory
char name[4]
Only reads 4characters