You are on page 1of 51

Chapter 09

File

Dr. Lê Thanh Sach


Dr. Tran Tuan Anh

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 1
© 2016
Contents
 Why we need to use file?
 Model of a file
 File classification
 Mandatory operators
 Read and write a file
 Text file
 Read, write, read and write
 Binary file
 Read, write, read and write
 Functions for file processing
 Examples
 Conclusion
Trường Đại Học Bách Khoa Lập trình C/C++
Trung Tâm Kỹ Thuật Điện Toán 2
© 2016
Why we need to use file?
 When a program terminates execution, the associated data
variables will be cleared from the main memory (RAM) of
the computer.
 To prevent data loss when the program ends, the program needs to
save them as files to storage devices such as hard drives, CDs,
DVDs, etc.

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 3
© 2016
Model of a file
 A file is a sequence of data bytes, as shown in the figure,
ending with a special EOF
EOF (End Of File): is a special value, not identical to
any value of byte data.
EOF: The notation that the function reads the data
returns to indicate the end of the file.
 (In many system/complier EOF=-1)

… EOF

1 2 3 N

N bytes data in Model

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 4
© 2016
File classification
 Text file
 Readable and understandable by human
 Can open, read/change by some office programs like NOTEPAD.

 Binary file
 Created by some programming, Human cannot read and
understand directly by NOTEPAD

 Use for some specify programs.

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 5
© 2016
Mandatory operators
 (1) Declaration
 (2) Open
 Function: fopen, fgetc
 (3) Implement
 Read or/and write
 (4) Close
 Function: fclose,

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 6
© 2016
Mandatory operator
The marker of a file

N bytes data in Model


1 2 3 N
… EOF

After open the file successfully, the marker will point to the first byte of the file

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 7
© 2016
Mandatory operator
The marker of a file

N bytes data in Model


1 2 3 N
… EOF

After reading 1 byte data, for example using: fgetc function

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 8
© 2016
Mandatory operator
The marker of a file

N bytes data in Model


1 2 3 N
… EOF

After one more byte

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 9
© 2016
Mandatory operator
The marker of a file

N bytes data in Model


1 2 3 N
… EOF

Read successfully N byte.

The next byte will return to EOF (-1)

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 10
© 2016
Text file: Read the file
Requirement

Input: text file


(readable)

Program: read the information


Program
from the file and save to the
buffer

Output: print to the


screen console

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 11
© 2016
Text file: Read
Idea

CH = Read a character

false
CH <> EOF

true
Save CH to buffer
CH = Read a character

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 12
© 2016
Text file: Read
(1) file pointer declaration

FILE* file_ptr = NULL;

Pointer to a file, a name

Data type: FILE


Defined in <stdio.h>
 Should include #include <stdio.h>
Trường Đại Học Bách Khoa Lập trình C/C++
Trung Tâm Kỹ Thuật Điện Toán 13
© 2016
Text file: Read
(2) Open file

FILE* file_ptr = NULL;


file_ptr = fopen("test.txt", "r");
if(file_ptr == NULL){
perror(“opening Error: ");
system("pause");
exit(EXIT_FAILURE);
}

• Open file by using: fopen


• Name of the file: "test.txt”
• Open file for reading: ”r”  (read)
• Checking file_ptr is NULL or not
• = NULL cannot open file

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 14
© 2016
Text file: Read
(2) Open file
FILE* file_ptr = NULL;
file_ptr = fopen("test.txt", "r");
if(file_ptr == NULL){
perror(“Error: ");
system("pause");
exit(EXIT_FAILURE);
}

"test.txt”: the program tries to find this file in the recent folder
which contains the cpp files, or in the directory of the PATH.

If we use the path, please use “\\” in stead of “\”; Because “\” is a
control character in string.

For instance: Using C:\\DATA\\Test.txt instead of: C:\DATA\Test.txt

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 15
© 2016
Text file: Read
(2) Open file - mode

Mode Description
r Only for reading
w For writing. If the file exists, the content will be removed.
a Open the existence file or create a new one, write the data at the end
of the file if it existed.
r+ Open the existence file to write or read. Do not create a new one if the
file does not exists.
w+ Open the existence file to write or read. Create a new one if it does not
exists.
a+ Open the existence file or create a new one, write the data at the end
of the file if it existed. Create a new one if it does not exists.

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 16
© 2016
Text file: Read
(3) Read all of the data in the file
void read_file(FILE* file_ptr, char* buffer){
int index = 0;

int ch = fgetc(file_ptr);
while(ch != EOF){
buffer[index] = ch;
ch = fgetc(file_ptr);
index += 1; CH = Read a character

}
buffer[index] = '\0'; CH <> EOF
false
}
true
fgetc: read a character Add CH to the buffer
CH = read a character

Suppose that the buffer size is large enough

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 17
© 2016
Text file: Read
(3) Read all of the data in the file
void doc_tap_tin(FILE* file_ptr, char* buffer){
int index = 0;

int ch = fgetc(file_ptr);
while(ch != EOF){
if(index < MAX_LEN - 1){
buffer[index] = ch;
ch = fgetc(file_ptr);
index += 1;
}
else break;
}
• Index lager than the size of
buffer[index] = '\0';
buffer: break
}

In the case we want to check the • Add the end index for the buffer
size of the buffer

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 18
© 2016
Text file: Read
(3) Read all of the data in the file
 function fgetc:
 Input the pointer to the file
 Return the int data type

 If the return value is EOF:end of the file


 Else:
 fgetc return the character/value (maybe type casting to unsigned

char) (0, .., 255)


 Fgetc: set the marker at the next byte on the file to read the next

character.

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 19
© 2016
Text file: Read
(4) Close
• Close the file by using: fclose

fclose(file_ptr);

printf("%s", buffer);

• Print the buffer to the console

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 20
© 2016
Text file: read
An example program
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 1024
int main(){
//Open file
FILE* file_ptr = NULL;
file_ptr = fopen("test.txt", "r");
if(file_ptr == NULL){
perror(“Error: ");
system("pause");
exit(EXIT_FAILURE);
}
//Read file
char buffer[MAX_LEN];
In the
doc_tap_tin(file_ptr, buffer);
previous slide
//Close file
fclose(file_ptr);
printf("%s", buffer);
system("pause");
Trường Đại Họcreturn
Bách Khoa EXIT_SUCCESS; Lập trình C/C++
Trung Tâm Kỹ Thuật Điện Toán 21
}
© 2016
Text file: read
Other functions
Function Description
fopen Open the process flow of a file
fclose Close the process flow of a file
fscanf Read the data type: char, int, float v.v. from the file.
fprintf Print the data type: char, int, float, v.v. to the file.
rewind Return the marker byte in the file to the beginning position to re-read
the file many times without re-open/re-close step.
fgets fgets (char* str, int num, FILE* stream)
Try to understand by your self
fputs Hàm fputs (const char* str, FILE* stream)
Try to understand by your self
All of the above function belong to stdio.h

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 22
© 2016
Text file: write
The progress is similar with reading

Step Read Write


(1) Declaration FILE *file_ptr FILE *file_ptr
(2) Open file_ptr = file_ptr =
fopen("test.txt", fopen("test.txt",
"r"); "w");

(4) Close fclose(file_ptr) fclose(file_ptr)

The difference is the step (3)

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 23
© 2016
Text file: write
Problem

 Suppose that we need to create a program to read and


write a file in the following format:

Nguyen Van A :9.8 , 7.2, 9.5


Tran Van B :4.0 , 5.3, 2.5
Phan Dinh C :8.7 , 7.9, 8.1

 Problem analysis:
 The content in a row: Name, 3 grade columns (real number). The
width of each column is fixed
 fprintf function have the same properties of printf (apply to write
the data to the file)  can use.

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 24
© 2016
Text file: write
Problem

 Problem analysis :
 Define the struct data type to manage the information of a student

typedef struct{
char name[20];
float math, physics, english;
} Student;

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 25
© 2016
Text file: write
Problem

 Problem analysis s:
 Declare the list of students:

Student list[] = {
{"Nguyen Van A", 9.8f, 7.2f, 9.5f},
{"Tran Van B", 4.0f, 5.3f, 2.5f},
{"Phan Dinh C", 8.7f, 7.9f, 8.1f},

};

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 26
© 2016
Text file: write
Problem

 Problem analysis:
 The main idea: scan each element in the list and write down to the
file.

for(int i=0; i< 3; i++){


fprintf(file_ptr, "%-15s:%-5.1f,%5.1f,%5.1f\n",
list[i].name,
list[i].math, list[i].physics, list[i].english);
}

file_ptr: file address

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 27
© 2016
Text file: write
Problem – An example
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 1024

typedef struct{
char name[20];
float math, physics, english;
} Student;

int main(){
Student list[] = {
{"Nguyen Van A", 9.8f, 7.2f, 9.5f},
{"Tran Van B", 4.0f, 5.3f, 2.5f},
{"Phan Dinh C", 8.7f, 7.9f, 8.1f},

};

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 28
© 2016
Text file: write
Problem – An example
FILE* file_ptr = NULL;
file_ptr = fopen("data.txt", "a");
if(file_ptr == NULL){
perror(« Error: ");
system("pause");
exit(EXIT_FAILURE);
}
for(int i=0; i< 3; i++){
fprintf(file_ptr, "%-15s:%-5.1f,%5.1f,%5.1f\n",
list[i].name,
list[i].math, list[i].physics, list[i].english);
}

fclose(file_ptr);
system("pause");
return EXIT_SUCCESS;
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 29
© 2016
Formatted text file: read
Problem

Read the formatted text file

Nguyen Van A :9.8 , 7.2, 9.5


Tran Van B :4.0 , 5.3, 2.5
Phan Dinh C :8.7 , 7.9, 8.1

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 30
© 2016
Formatted text file: read
Operations

int main(){
Student list[100];
int size = 0;

FILE* file_ptr = NULL; 1. Pointer File declaration


mo_tap_tin(&file_ptr, "data.txt"); 2. Open file
size = doc_du_lieu(file_ptr, list); 3. Read formatted file
dong_tap_tin(file_ptr); 4. Close file
in_du_lieu(list, size); 5. Print out

system("pause");
return EXIT_SUCCESS;
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 31
© 2016
Formatted text file: read
Operations

Data type and function prototype

typedef struct{
char name[20];
float math, physics, english;
} Student;

void mo_tap_tin(FILE** file_ptr, char tap_tin[]);


void dong_tap_tin(FILE* file_ptr);

bool doc_ten(FILE* file_ptr, char* name, char end_char);


bool doc_diem(FILE* file_ptr, float *math, float *physics, float *english);
bool xoa_xuong_hang(FILE* file_ptr);
int doc_du_lieu(FILE* file_ptr, Student list[]);
void in_du_lieu(Student list[], int size);

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 32
© 2016
Formatted text file: read
Operations

Open file for reading

void mo_tap_tin(FILE** file_ptr, char tap_tin[]){


*file_ptr = fopen(tap_tin, "r");
if(*file_ptr == NULL){
perror(« Error: ");
system("pause");
exit(EXIT_FAILURE);
}
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 33
© 2016
Formatted text file: read
Operations

Open and close file (read)

void mo_tap_tin(FILE** file_ptr, char tap_tin[]){


*file_ptr = fopen(tap_tin, "r");
if(*file_ptr == NULL){
perror(« Error: ");
system("pause");
exit(EXIT_FAILURE);
}
}

void dong_tap_tin(FILE* file_ptr){


fclose(file_ptr);
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 34
© 2016
Formatted text file: read
Operations
int doc_du_lieu(FILE* file_ptr, Student list[]){
int size =0;
bool doc_tiep = true;
while(doc_tiep){
doc_tiep = doc_ten(file_ptr, list[size].name, ':');
if(!doc_tiep) break;
doc_tiep = doc_diem(file_ptr,
&list[size].math,
&list[size].physics, &list[size].english);
if(!doc_tiep) break;

doc_tiep = xoa_xuong_hang(file_ptr);
size += 1;

if(!doc_tiep) break;

}//while
return size;
Reading progress
}
Trường Đại Học Bách Khoa Lập trình C/C++
Trung Tâm Kỹ Thuật Điện Toán 35
© 2016
Formatted text file: read
Operations

bool doc_ten(FILE* file_ptr, char* name, char end_char){


int i = 0;
int ch = fgetc(file_ptr);
while((ch != ':') && (ch != EOF)){
name[i] = ch;
i += 1;
ch = fgetc(file_ptr);
}
name[i] = '\0';

if(ch == EOF) return false;


else return true;
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 36
© 2016
Formatted text file: read
Operations

bool doc_diem(FILE* file_ptr,


float *math, float *physics, float *english){
int num = fscanf(file_ptr, "%f , %f, %f",
math,
physics,
english);
if(num != 3) return false;
else return true;
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 37
© 2016
Formatted text file: read
Operations

bool xoa_xuong_hang(FILE* file_ptr){


int ch;
ch = fgetc(file_ptr);
while((ch != EOF) && (ch == '\n') ){
ch = fgetc(file_ptr);
}
if(ch == EOF) return false;
else{
fseek(file_ptr, -1, SEEK_CUR);
return true;
}
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 38
© 2016
Formatted text file: read
Operations

void in_du_lieu(Student list[], int size){


for(int i=0; i< size; i++){
printf("%-20s:%-5.1f,%5.1f,%5.1f\n",
list[i].name,
list[i].math,
list[i].physics,
list[i].english);
}
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 39
© 2016
Read and write a file
 Two main operators
 Write
 Read.
 Write
 Using library:
 For text file: fprintf, fputs

 For binary file: fwrite

 Writing operation is little bit easier than read.


 For text file: fprintf similar to printf:

 %s: for string, can set width,…

 %f: for number, can set the precision

 V.v

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 40
© 2016
Read and write a file
 Write
 For binary file: fwrite.
 This function can describe the number or the size of each

element (the element maybe a struct or array)

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 41
© 2016
Read and write a file
 Read
 Reading is often harder than writing
 A good reading function:
 Can work with many structures file (or when the structure of a

file is changed)
 With binary file:
 We do not know the length of the file

  So we need to read all of the element of the file (up to

EOF or reach the error)


 With text file:
 Depend on the structure

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 42
© 2016
Binary file: Read
Operation

int main(){
Student list[MAX_SIZE];
int size;

size = sinh_du_lieu_mau(list);
ghi_du_lieu(list, size, "stu_list.data");
in_du_lieu(list, size);

printf("\n\n");
system("pause");
return EXIT_SUCCESS;
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 43
© 2016
Binary file: Read
Operation

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_SIZE 100

typedef struct{
char name[20];
float math, physics, english;
} Student;

int sinh_du_lieu_mau(Student *list);


void ghi_du_lieu(Student *list, int size, char* file);
void in_du_lieu(Student *list, int size);

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 44
© 2016
Binary file: Read
Operation

int sinh_du_lieu_mau(Student *list){


time_t t;
srand((unsigned int) time(&t));
for(char c='A'; c <= 'Z'; c++){
list[c - 'A'].name[0] = c;
list[c - 'A'].name[1] = '\0';
list[c - 'A'].math = ((float)rand()/RAND_MAX)*10;
list[c - 'A'].physics = ((float)rand()/RAND_MAX)*10;
list[c - 'A'].english = ((float)rand()/RAND_MAX)*10;
}
return ('Z' - 'A' + 1);
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 45
© 2016
Binary file: Read
Operation

void ghi_du_lieu(Student *list, int size, char* file){


FILE* file_ptr = NULL;
file_ptr = fopen(file, "ab+");
if(file_ptr == NULL)
exit(EXIT_FAILURE);

fwrite(list, sizeof(Student), size, file_ptr);


fclose(file_ptr);
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 46
© 2016
Binary file: Read
Operation

void in_du_lieu(Student *list, int size){


for(int i=0; i< size; i++){
printf("%-20s:%-5.1f,%-5.1f,%-5.1f\n",
list[i].name,
list[i].math,
list[i].physics,
list[i].english);
}
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 47
© 2016
Binary file: Read
Operation

Open file

FILE* file_ptr = NULL;


file_ptr = fopen(file, "rb");
if(file_ptr == NULL){
perror("Error in open file: ");
system("pause");
exit(EXIT_FAILURE);
}

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 48
© 2016
Binary file: Read
Operation

Read profiles

int c= 0;
int num = 0;
while(true){
num = fread(&list[c], sizeof(Student), 1, file_ptr);
if(num != 1){
break;
}
c++;
}
*size = c;

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 49
© 2016
Binary file: Read
Operation

Close file

fclose(file_ptr);

Trường Đại Học Bách Khoa Lập trình C/C++


Trung Tâm Kỹ Thuật Điện Toán 50
© 2016
Binary file: Read
Operation
void doc_du_lieu(Student *list, int *size, char* file){
FILE* file_ptr = NULL;
file_ptr = fopen(file, "rb");
if(file_ptr == NULL){
perror("Error in open file: ");
system("pause");
exit(EXIT_FAILURE);
}
int c= 0;
int num = 0;
while(true){
num = fread(&list[c], sizeof(Student), 1,
file_ptr);
if(num != 1){
break;
}
c++;
}
*size = c;
Trường Đại Họcfclose(file_ptr);
Bách Khoa Lập trình C/C++
Trung Tâm Kỹ Thuật Điện Toán 51
}
© 2016

You might also like