Week 2
Week 2
Week 2
html
C Programming
Basic – week 2
For HEDSPI Project
Lecturers :
Cao Tuan Dung
Le Duc Trung
Dept of Software Engineering
Hanoi University of Technology
Topics
• Structures, dynamic allocation
review
int main()
{
char *str;
/* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}
len1 = strlen(str1);
len2 = strlen(str2);
strcpy(result, str1);
strcpy(result + len1, str2);
return result;
}
Solution: main()
int main(void)
{
char str1[MAX_LEN + 1], str2[MAX_LEN + 1];
char *cat_str;
scanf("%100s", str1);
scanf("%100s", str2);
return 0;
}
Homework ICT55
• Implement and demo the function
– char* subStr(char* s1, int offset, int
number)
• This function take the subString of s1
that starts from the character with
offset index and has number
characters.
• Remember to check the validation of
the parameters. In the case that the
number is greater than the number of
characters resting from offset to the
end of s1. Return the subString of s1
from offset.
Structures - User Defined
Types
• A collection of variables under a
single name.
• A convenient way of grouping several
pieces of related information
together.
• Variables in a struct (short for
structure) are called members or
fields.
Defining a struct
struct struct-name
{
field-type1 field-name1;
field-type2 field-name2;
field-type3 field-name3;
...
};
Example – complex
numbers
struct complex {
int real;
int img;
};
struct complex num1, num2,
num3;
Typedef
• We can combine the typedef with the
structure definition:
int main(void)
{
point_t p;
circle_t c;
if (is_in_circle(&p, &c))
printf("point is in circle\n");
else
printf("point is out of circle\n");
return 0;
}
Bài tập Bổ sung
• Viết hàm kiểm tra hai đường tròn có giao
nhau hay không.
• Viết chương trình hỏi người dùng muốn
sinh bao nhiêu đường tròn. Lưu trữ vào bộ
nhớ động. Người dùng lựa chọn
– Nhập bằng tay
– Sinh tự động (ngẫu nhiên).
• In ra thông tin về các đường tròn
• In ra đường tròn giao nhau với nhiều
đường tròn khác nhất (in ra thông tin chi
tiết – giao với đường nào)
Pointers in Structures
• If a member in a struct is a pointer,
all that gets copied is the pointer
(the address) itself
• Exercise: Give this type of Student
Bài tập I:
• Cải tiến Bài tập II – Tuần trước (Bài
tập Danh sách lớp – Bảng điểm).
• Dùng con trỏ và cấp phát động.
• Không dùng mảng.
main(void) {
FILE *fptr1, *fptr2;
char filename1[]= "lab1a.txt";
char filename2[]= "lab1.txt";
int reval = SUCCESS;
while (!feof(fin)){
num = fread(buff, sizeof(char),
MAX_LEN, fin);
buff[num * sizeof(char)] = `\0';
printf("%s", buff);
fwrite(buff, sizeof(char), num, fout);
}
}
Exercise
• Write program mycat that works like
the command cat in Unix
• Using fread funtion.
Bài tập về nhà 3
• Cải tiến chương trình mycat viết trên
lớp cho phép xem nội dung file theo
trang khi kích thước file lớn.
• Tham số -p.
Solution
#include <stdio.h>
enum {SUCCESS, FAIL, MAX_LEN = 80};
void BlockCat(FILE *fin);
while (!feof(fin)){
num = fread(buff, sizeof(char),
MAX_LEN, fin);
buff[num * sizeof(char)] = `\0';
printf("%s", buff);
}
}
Bài tập về nhà 2
• Viết chương trình copy-multimode với giao
diện menu dòng lệnh cho phép lựa chọn
• 1. Sao chép theo ký tự
• 2. Sao chép theo dòng
• 3. Sao chép theo block – kích thước tùy
chọn
• Sau khi kết thúc sao chép in ra thời gian
thực hiện việc sao chép để so sánh.
• Ghi chú: Chọn file nguồn là một file văn
bản kích thước lớn (từ 640K trở lên).
Exercise
• A)Improve the program in previous exercise so
that it accepts the two filenames as command
arguments.
int main(void)
{
FILE *fp;
phoneaddress phonearr[MAX_ELEMENT];
int i,n, irc; // return code
int reval = SUCCESS;
Solution
printf("How many contacts do you want to enter (<20)?");
scanf("%d", &n);
for (i=0; i<n; i++){
printf("name:"); scanf("%s",phonearr[i].name);
printf("tel:"); scanf("%s",phonearr[i].tel);
printf("email:"); scanf("%s",phonearr[i].email);
}
if ((fp = fopen("phonebook.dat","w+b")) == NULL){
printf("Can not open %s.\n", "phonebook.dat");
reval = FAIL;
}
int main(void)
{
FILE *fp;
phoneaddress *phonearr;
// Memory allocation
phonearr =
(phoneaddress *)malloc(2 * sizeof(phoneaddress));
if (phonearr == NULL)
{
printf("Memory allocation failed!\n");
return FAIL;
}
if (fseek(fp,1*sizeof(phoneaddress),SEEK_SET) != 0)
{
printf("Fseek failed!\n");
return FAIL;
}
irc = fread(phonearr, sizeof(phoneaddress), 2, fp);
Solution
for (i=0; i<2; i++){
printf("%s-",phonearr[i].name);
printf("%s-",phonearr[i].tel);
printf("%s\n",phonearr[i].email);
}
fseek(fp,1*sizeof(phoneaddress),SEEK_SET);
irc = fwrite(phonearr, sizeof(phoneaddress), 2, fp);
printf(" fwrite return code = %d\n", irc);
fclose(fp); free(phonearr);
return reval;
}
Bài tập về nhà
• Truy nhập Trang thegioididong.vn
• Lấy thông tin các điện thoại di động Nokia và ghi
vào file: NokiaDB.txt theo format sau (trên 1
dòng)
• Model DungluongBonho KichthuocManhinh
Giatien
• Viết chương trình chứa menu
– 1. Import DB from text: Viết chương trình tự động
(dùng bộ nhớ động) chuyển NokiaDB.txt thành
NokiaDB.dat.
– 2. Import from DB: Đọc từ file. dat ra. Hỗ trợ chế độ
đọc toàn phần và đọc một phần từ 2 vị trí đầu và cuối
(chọn số phần tử và vị trí đọc từ đầu hoặc cuối).
– 3. Print All Nokia Database: Đọc dữ liệu từ
NokiaDB.dat -→ màn hình. Nếu nhiều hơn một màn
hình thì phải phân trang
– 4. Tìm kiếm điện thoại: Theo Model.
– 5. Exit
Bài tập về nhà
• Tạo file phone.dat theo thông tin trong danh
bạ điện thoại của bản thân (20 số liên lạc)
hoặc file grade.dat
• Viết chương trình filesplit nhận hai tham số:
tên file và số các liên lạc muốn tách, tên 2
file tách.
• Tách danh bạ làm hai phần.
• Ví dụ
– filesplit phone.dat 10 phone1.dat phone2.dat
• Sau đó viết chương trình mergefile theo cú
pháp
– filemerge phone1.dat phone2.dat phone.dat
• Viết chương trình fileread để đọc nội dung
các file .dat trên, dùng vào việc kiểm tra kết
quả.
Formatted Input Output
• Two function fprintf and fscanf
• Work as printf and scanf.
int fscanf(FILE *stream, const char *format, …);
int fprintf(FILE *stream, const char *format, …);
int main(void)
{
FILE *fp;
int *p;
int i,n, value, sum;
int reval = SUCCESS;