CLang Lect14
CLang Lect14
CLang Lect14
1
Standard input/output streams
• 3 standard streams are opened by a program:
• stdin: for input
• stdout: for output
• stderr: for error
• The direction of these streams to peripherals
depends on the program, the default is keyboard for
stdin, screen for stdout and stderr
• scanf() and printf() are functions that read/write in
stdin and stdout
• perror() prints the errors to stderr
2
Example
Input.c
#include <stdio.h> $input
void main() 10
{ Input number10
$input
int a;
abc
if ( scanf("%d", &a) != 1 ) This is not integer
perror(“This is not integer\n”); $input >out.txt
else 10
$input >out.txt
printf(“Input number%d", a); abc
} This is not integer
3
Input/output file
• Files need to be opened before use.
• Associate a "file handler" to each file
• Modes: read, write, or append
• File input/output functions use the file handler (not
the filename).
• Need to close the file after use.
• Basic file handling functions: fopen(), fclose(),
fscanf(), fprintf().
• FILE * is the file handler type
4
Example
#include <stdio.h>
if (out == NULL)
{
perror(“Unable to write to the file.\n”);
return 1;
}
Write data to
fprintf(out, “Hello world”); file
fclose(out);
5
Modes in open file
• r: read
• w: write
• a: append
• r+: read/write on a new file if not exist
• w+: write on a new file if not exist
• a+: append on a new file if not exist
6
fprintf() và printf()
• fprintf works exactly as printf except the output on
stdout.
• printf(…) = fprintf(stdout, …)
• Similarly we have other output streams:
• fputs(char*, FILE*) and puts(char*)
• fputc(char, FILE*) and putchar(char)
7
fscanf() and scanf()
• fscanf work exactly as scanf except the
input on stdin.
• The return type of fscanf() and scanf() is the number
of elements read.
• Similarly we have other input streams:
• char* fgets(char*, int maxlen, FILE*) and
• char*gets(char*);
• int fgetc(FILE*) and int getchar(void)
8
Input data
• Both scanf() and fscanf() return:
• the number of input items converted and assigned successfully
• or the constant value EOF when an error or end-of-file occurs
• Therefore we can also check EOF using function fscanf
• The input process is the process of scanning data on the
buffer according to a specific data type.
• After each successful scan, the buffer’s pointer shifts to the
next space in order to scan data for the next reading time.
• When there is no more data in the buffer, the buffer’s pointer
points to EOF.
• To check whether the pointer is at the EOF position or not, using
function int feof(FILE*)
9
Input formats
• Input number following formats %d, %l, %x,…, will skip
spaces and
• %s scans a string not including spaces and .
• %c scans any character at the pointer’s position (including
spaces and )
• Example, if we enter “12 ab”
• "%d%s" gives us a number 12 and a string “ab”
• "%d%c%s" gives us a number 12, a space and a string
“ab”
• "%d %c%s" gives us a number 12, a character a and a
string “b”
• "%s%s" gives us two strings “12” and “ab”
• "%d%s%c" give us a number 12, a string “ab”
and a character
10
fflush()
• Function fflush(<stream>) is used to clean an
input/ouput buffer
• When a file is closed, its buffer will be automatically
cleaned
• fflush() should be used before scanning a character or
a string with gets() or fgets()
• Like enter a character, gets() does not skip any
character when scanning. This function scans all
spaces and stops at the first . However, does not
include in the target string.
11
Example
Input.c
#include <stdio.h>
C:\>input
Input a number: 12
void main() Input a string: ab
{ number 12, string ab
int a;
char s[20];
printf(“Input a number: ”);
scanf(“%d”, &a);
%d only gets two
characters ’12’ to convert
fflush(stdin);
to number, the redundant
printf(“Input a string: “);
character is cleaned by
gets(s);
fflush() before enter a
string by gets()
printf(“number %d, string %s”,
a, s);
}
12
Calculate total words of a file
#include <stdio.h>
int main()
{ Open file to
int count = 0; read
char s[80];
FILE * f = fopen(“text.txt”, “r”);
if (f == NULL)
{
perror(“Failure when opening text file.txt\n”);
return 1;
} Read a word
while (!feof(f)) each time
dem += fscanf(f, “%s”, s);
fclose(f);
printf(“Total number of words: %d”, dem);
return 0;
}
13
fgetc() and fputc()
FILE *input, *output;
input = fopen( "tmp.c", "r" );
output = fopen( "tmpCopy.c", "w+" );
ch = fgetc( input );
while( ch != EOF ) {
fputc( ch, output );
ch = fgetc( input );
}
fclose(input);
fclose(output);
14
fgets()
#include <stdio.h>
#define LINE_LENGTH 80
main()
{
FILE* fp;
char line[LINE_LENGTH];
int count=0;
fp=fopen("input.txt","r");
while ( fgets(line, LINE_LENGTH, fp) != NULL)
count++;
printf("File contains %d lines.\n", count);
fclose(fp);
}
15
Text file vs. binary file
• There is no difference among byte data in binary
file
• In text file, byte data are categorized as displayed
character and control character.
• A text file is marked as end by a control character
(e.g., 26 in DOS)
• To open a file in text mode, we add ‘t’ in the open
mode ("r+t", "wt", ...).
• To open a file in binary mode, we add ‘b’ in the
open mode ("r+b", ...).
16
Input/ouput in binary mode
size_t fread(void* buf, size_t size,
size_t num, FILE* f);
size_t fwrite(void* buf, size_t size,
size_t num, FILE* f);
• Read and write data in the memory with the pointer buf, with the
total elements num, size of each element size
Example:
int a[10];
f=fopen("integer.dat", "r+b");
fread(a, 10, sizeof(int), f);
17
Exercises
1. Write a program to create a text file F3 by concatenate two text files F1
and F2
F1 = “ha noi”; F2 = “ viet nam” F3 = “ha noi viet nam”
2. Write a program to remove all comments from a C program which is
stored in a file. The name of the file is entered from the keyboard. Assume
that the program does not have syntax errors.
3. Assume that a data file consisting information about weather in a year has
the format for each line as follow: \
<day>/<month> <lowest temperature>-<highest temperature> <humidity>
1/1 11-17 70
2/1 12-17 75
…
4. Write a program read data from this file and print the average temperature
of all months in a year, the most humid month and the dryest month.
18
Thank you
for your
attentions!