0% found this document useful (0 votes)
19 views19 pages

CLang Lect14

The document discusses input and output streams in C programs. It covers: 1. The 3 standard streams - stdin, stdout, and stderr and their default uses. Functions like scanf(), printf(), and perror() for reading from and writing to these streams. 2. Opening, reading from, and writing to files using functions like fopen(), fclose(), fscanf(), fprintf(), gets(), and fputs(). Modes like r, w, a for opening files. 3. Examples of reading user input, writing to files, counting words in a file, copying files using functions like fgetc(), fputc(), fgets(), fread(), and fwrite().

Uploaded by

Thành
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views19 pages

CLang Lect14

The document discusses input and output streams in C programs. It covers: 1. The 3 standard streams - stdin, stdout, and stderr and their default uses. Functions like scanf(), printf(), and perror() for reading from and writing to these streams. 2. Opening, reading from, and writing to files using functions like fopen(), fclose(), fscanf(), fprintf(), gets(), and fputs(). Modes like r, w, a for opening files. 3. Examples of reading user input, writing to files, counting words in a file, copying files using functions like fgetc(), fputc(), fgets(), fread(), and fwrite().

Uploaded by

Thành
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Input/output file

Department of Information System


SoICT, HUST

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

Redirect stdout to file


out.txt

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>

int main() Open file to


{ write
FILE * out = fopen(“hello.txt”, “w”);

if (out == NULL)
{
perror(“Unable to write to the file.\n”);
return 1;
}
Write data to
fprintf(out, “Hello world”); file
fclose(out);

return 0; Close file when


} terminate

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!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy