0% found this document useful (0 votes)
32 views27 pages

NMLT Topic 9 File

The document discusses file input/output in programming. It begins by defining two main file types - text files and binary files. It then provides details on opening, reading, writing, and closing files. The key steps outlined are opening the file, using the file by reading/writing data, and closing the file. Common functions for file I/O like fopen(), fread(), fwrite(), fclose() are also explained.

Uploaded by

trung2003lucky
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)
32 views27 pages

NMLT Topic 9 File

The document discusses file input/output in programming. It begins by defining two main file types - text files and binary files. It then provides details on opening, reading, writing, and closing files. The key steps outlined are opening the file, using the file by reading/writing data, and closing the file. Common functions for file I/O like fopen(), fread(), fwrite(), fclose() are also explained.

Uploaded by

trung2003lucky
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/ 27

University of Science, VNU-HCM

Faculty of Information Technology

Introduction to Programming

File

Lecturer: Le Ngoc Thanh


Email: [email protected]

HCM City 1
Content

1 File types

2 Input-Output System

3 Manipulation on Raw files

4 Use files to store data

2
Introduction
• The programming with the file aims to store
the program's data into the secondary
memory and retrieve this data back when
necessary.
• Usually data storage is the file on disk.
• Two main file types are considered:
– Text File
– Binary file

3
Text File
• This is the most simple and common structured
text file, which can be viewed and repaired
using the operating system commands or
simple text editor programs.
• Is normally stored on disk as .txt.
• Most of the program's source code is stored on
disk as a text file.
• Content composed of 8-bit characters
– These characters are found to have code from 0x20
or higher.
– The control characters have a code that is less than
0x20
4
Expanded text file
• Unicode characters or multi-byte characters
can be saved.
• The two most common expanded crude text
structures are:
– Unicode text: Saves UTF-16 characters.
– UTF-8: Saves the character length fluctuations
from 1 to 4 bytes.

5
Binary files
• Are unstructured files such as raw text files.
• Each file consists of a range of data bytes,
including two types:
– Sequential bytes are not mutually relevant in
terms of organizational structure files.
– Is structured according to the convention of the
file creation software.

6
Steps to working with file
• Includes 3 main steps:
– Step 1. Open the file, the programmer needs to
include the correct path and file name.
– Step 2. Use the file (after successfully opening
the file).
 Read data from the file inserted into the memory
variable in the program.
 Write data from the memory variable in the program
File.
– Step 3. Close the file (after completing the
necessary tasks).

7
Open File function

FILE *fopen(const char *filename, const char *mode)

Open the file named (path) is contained in


the filename with the type open mode (see
table).

Success: structure-style pointers FILE


Fail: NULL (Wrong rule named file, no
drive found, folder not found, open files not
yet available for reading,...)
FILE* fp = fopen(“myFile.txt”, “rt”);
if (fp == NULL)
printf(“Can not open file!”);

8
Arguments in openning file (mode)

Arguments Meaning
b Open binary file type
t Open the text file (default)
r Open the file only to read data from the file. Returns NULL
if file not found.
w Open the file just to write the data to the file. The file will
be created if it is not already, the previous data is erased.
a Open the file only to add (append) data to the end of the
file. The file will be created if it is not already.
r+ Like the R mode and add the data recording feature and
the file will be created if not already.
w+ Same mode W and additional read feature.
a+ Same mode A and additional reading features.

9
Reading and writing data (stdio.h)
• Perform reading/writing data in the following
ways:
• Import/Export as Format
– Function: fscanf, fprintf
– Use only with text files.
• Import/export each character or line up file
– Function : getc, fgetc, fgets, putc, fputs
– Should only be used with text styles.
• Read/write data directly from memory-file
– Function : fread, fwrite
– Only used with binary file type.

10
Output with format

int fprintf(FILE *fp, char *fnt, …)

Writes data in string format fnt (similar to


the printf function) into stream fp.
If fp is stdout, the function is the same as
printf.
Success: returns the number of bytes
written.
Fail: return EOF (has value -1, defined in
STDIO.H, for use in text files)
int i = 2912; int c = ‘P’; float f = 17.06;
FILE* fp = fopen(“output.txt”, “wt”);
if (fp != NULL)
fprintf(fp, “%d %c %.2f\n”, i, c, f);

11
Input with format

int fscanf(FILE *fp, char *fnt, …)

Read data in string format fnt (similar to the


scanf function) from stream fp.
If fp is stdin, the function is the same as
scanf
Success: Returns the number of readable
elements.
Fail: return EOF.
int i;
FILE* fp = fopen(“input.txt”, “rt”);
if (fp != NULL)
fscanf(fp, “%d”, &i);

12
Read a character

int getc(FILE *fp) và int fgetc(FILE *fp)

Read a character from stream fp.


getc is macro while fgetc is function of
macro getc.
Success: returns the character read from
the file after converting to an unsigned
integer.
Fail: return EOF when finish fp or error.
char ch;
FILE* fp = fopen(“input.txt”, “rt”);
if (fp != NULL)
ch = getc(fp); //  ch = fgetc(fp);

13
Read a string

int fgets(char *str, int n, FILE *fp)

Reads a sequence of characters from


stream fp into str, ends when n-1
characters or meets a newline.

Success: return str.


Fail: return NULL when you get an error or
EOF.
char s[20];
FILE* fp = fopen(“input.txt”, “rt”);
if (fp != NULL)
fgets(s, 20, fp);

14
Write a character

int putc(int ch, FILE *fp) và int fputc(in ch, FILE *fp)

Write character ch into stream fp.


putc is macro while fputc is function of
macro putc.

Success: return character ch.


Fail: return EOF.

FILE* fp = fopen(“output.txt”, “rt”);


if (fp != NULL)
putc(‘a’, fp); // or fputc(‘a’, fp);

15
Write a string

int fputs(const char *str, FILE *fp)

Write a string str into stream fp. If fp is


stdout, fputs is the same as puts, but puts
also write newline.

Success: return the last character written.


Fail: return EOF.

char s[] = “Intro to Programming”;


FILE* fp = fopen(“output.txt”, “wt”);
if (fp != NULL)
fputs(s, fp);

16
Write data in byte

int fwrite(void *buf, int size, int count, FILE *fp)

Write count times of data with size bytes


from buffer buf into stream fp.

Success: return the number of records


(not the number of bytes) written.
Fail: return the quantity less than count.
int a[] = {1, 2, 3};
FILE* fp = fopen(“output.dat”, “wb”);
if (fp != NULL)
fwrite(a, sizeof(int), 3, fp);

17
Read data in byte

int fread(void *buf, int size, int count, FILE *fp)

Read count of data with size bytes into


buffer buf from stream fp.

Success: return the number of records


(not the number of bytes) read.
Fail: return the quantity less than count or
error.
int a[5];
FILE* fp = fopen(“input.dat”, “rb”);
if (fp != NULL)
fread(a, sizeof(int), 3, fp);

18
Close file

int fclose(FILE *fp)

Close stream fp.


Data in stream fp will be written before
closing.

Success: return 0.
Fail: return EOF.

FILE* fp = fopen(“file.txt”, “rt”);



fclose(fp);

19
Close all stream

int fcloseall()

Close all open streams except standard


streams stdin, stdout, stdprn, stderr, stdaux.
Should close each stream instead of closing
all.
Success: return the number of closed
streams.
Fail: return EOF.
FILE* fp1 = fopen(“file1.txt”, “rt”);
FILE* fp2 = fopen(“file2.txt”, “wt”);

fcloseall();

20
Position indicator
• Position indicator
– Created automatically when opening the file.
– Determines where the reading / writing takes
place in the file.
• Position
– When the file is not open: the position indicator
will be at the beginning of the file (value 0).
– When the file is open :
 At the end of file when open for inserting (mode a or
a+)
 At the beginning of file (or value 0) when opening
with other modes (w, w+, r, r+).
21
Sequentially vs random access
• Sequentially access
– Data must be read / written from pointer
indicator to position n-1 before reading data at
position n.
– The position indicator is neglected because the
position indicator automatically moves to the
next position after a read / write operation.
• Random access
– Can read / write at any position in the file
without having to read / write all data
beforehand => using the position indicator.
22
Reset the position indicator

void rewind(FILE *fp)

Resets the position indicator to the


beginning (byte 0) of the file fp.

None

FILE* fp = fopen(“file.txt”, “w+”);


fprintf(fp, “0123456789”);
rewind(fp);
fprintf(fp, “*****”);

23
Change the position indicator

int fseek(FILE *fp, long offset, ing origin)

Change the position indicator in the stream fp


with offset positions from the origin position
(SEEK_SET or 0: beginning of file; SEEK_CUR or
1: current position; SEEK_END or 2: end of file)

Success: return 0.
Fail: returns a nonzero value.

FILE* fp = fopen(“file.txt”, “w+”);


fseek(fp, 0L, SEEK_SET); //  rewind(fp);
fseek(fp, 0L, SEEK_END); // end of file
fseek(fp, -2L, SEEK_CUR);// go back 2 positions

24
Determines the position of the position indicator

long ftell(FILE *fp)

The function returns the current position of


the position indicator (from the first position
of the file, i.e. 0) of the stream fp.

Success: returns the current position of


the indicator.
Fail: return -1L.
FILE* fp = fopen(“file.txt”, “rb”);
fseek(fp, 0L, SEEK_END);
long size = ftell(fp);
printf(“Size of file is %ld\n”, size);

25
Read Introduction to Programming Book (Page 323-331)

• Read the file.


• Create file to write data.
• Edit existing file.
• Add, merge files.
• Support operations
– Check if the file is available.
– Check the file for editing or not.
– Delete, rename files.

26
The End

You might also like