thư viện c

57
Thö Vieän C Y!M: [email protected] Mr.Vũ Kim Hiếu 1 Thư Viện C Hi! Đây là Thư viện các hàm trong C căn bản mà mình sưu tầm được! nó rất hay và hữu ích đó các bạn. Hi vọng bài viết này sẽ giúp ích cho các bạn trong việc học lập trình C. Thân! Mr.Vũ Hiếu. 1. In/Out Danh sách các hàm sử dụng In/Out 1.clearerr 2.fclose 3.feof 4.ferror 5.fflush 6.fgetc 7.fgetpos 8.fgets 9.fopen 10.fprintf 11.fputc 12.fputs 13.fread 14.freopen 15.fscanf 16.fseek 17.fsetpos 18.ftell 19.fwrite 20.getc 21.getchar 22.gets

Upload: thinh-ale

Post on 11-Apr-2015

33 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 1

Thư Viện C Hi! Đây là Thư viện các hàm trong C căn bản mà mình sưu tầm được! nó rất hay và hữu

ích đó các bạn. Hi vọng bài viết này sẽ giúp ích cho các bạn trong việc học lập trình C. Thân! Mr.Vũ Hiếu.

1. In/Out

Danh sách các hàm sử dụng In/Out 1.clearerr 2.fclose 3.feof 4.ferror 5.fflush 6.fgetc 7.fgetpos 8.fgets 9.fopen 10.fprintf 11.fputc 12.fputs 13.fread 14.freopen 15.fscanf 16.fseek 17.fsetpos 18.ftell 19.fwrite 20.getc 21.getchar 22.gets

Page 2: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 2

23.perror 24.printf 25.putc 26.putchar 27.puts 28.remove 29.rename 30.rewind 31.scanf 32.setbuf 33.setvbuf 34.sprintf 35.sscanf 36.tmpfile 37.tmpnam 38.ungetc 39.vprintf, vfprintf, and vsprintf Hàm clearerr Khai báo : Trích dẫn:

void clearerr(FILE *stream);

Xoá tín hiệu lỗi gây ra bởi hệ thống khi thao tác trên tập tin gặp lỗi . Example

Code:

#include <stdio.h>

int main(void)

{

FILE *fp;

char ch;

Page 3: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 3

/* mo tep tin de ghi */

fp = fopen("DUMMY.FIL", "w");

/*gay nen mot loi bang cach doc file*/

ch = fgetc(fp);

printf("%c\n",ch);

if (ferror(fp))

{

/* xuat ra man hinh thong bao loi */

printf("Error reading from DUMMY.FIL\n");

/* xoa tin hieu loi */

clearerr(fp);

}

fclose(fp);

return 0;

}

Hàm fclose Khai báo : Trích dẫn:

int fclose(FILE *stream);

Đóng tệp lại sau khi thao tác , stream là tên con trỏ tệp . Khi thành công hàm trả về 0 , trái lại trả về EOF ( hằng chỉ thị kết thúc tệp ) Example

Code:

#include <string.h>

#include <stdio.h>

int main(void)

{

FILE *fp;

char buf[11] = "0123456789";

fp = fopen("DUMMY.FIL", "w");

fwrite(&buf, strlen(buf), 1, fp);

/* dong tep */

fclose(fp);

return 0;

}

Hàm feof Khai báo : Trích dẫn:

Page 4: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 4

int feof(FILE *stream);

Hàm dùng để kiểm tra con trỏ tệp có đến cuối tệp hay chưa . Nếu nó đến cuối tệp thì hàm trả về giá trị khác 0 , ngược lại trả về 0 Example

Code:

#include <stdio.h>

int main(void)

{

FILE *stream;

/* mo mot tep de doc */

stream = fopen("DUMMY.FIL", "r");

/* doc mot ky tu tu tep */

fgetc(stream);

/*kiem tra xem cuoi tep hay chua */

if (feof(stream))

printf("We have reached end-of-file\n");

/* dong tep*/

fclose(stream);

return 0;

}

Hàm ferror Khai báo : Trích dẫn:

int ferror(FILE *stream);

Kiểm tra lỗi thao tác trên tệp . Hàm trả về giá trị khác 0 nếu có lỗi , ngược lại trả về 0 . Example :

Code:

#include <stdio.h>

int main(void)

{

FILE *stream;

/* mo tep de ghi */

stream = fopen("DUMMY.FIL", "w");

/* gay ra mot loi bang cach doc*/

(void) getc(stream);

if (ferror(stream)) /* kiem tra loi tren tep*/

{

/* ghi loi ra man hinh*/

printf("Error reading from DUMMY.FIL\n");

Page 5: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 5

/* xoa tin hieu loi*/

clearerr(stream);

}

fclose(stream);

return 0;

}

Hàm fflush Khai báo : Trích dẫn:

int fflush(FILE *stream);

Hàm dùng làm sạch vùng đệm của tệp . Nếu thành công hàm cho giá trị 0 , trái lại hàm trả về EOF Example Code:

#include <string.h>

#include <stdio.h>

#include <conio.h>

#include <io.h>

void flush(FILE *stream);

int main(void)

{

FILE *stream;

char msg[] = "This is a test";

/* tao 1 tep */

stream = fopen("DUMMY.FIL", "w");

/*ghi mot vai du lieu len tep */

fwrite(msg, strlen(msg), 1, stream);

clrscr();

printf("Press any key to flush DUMMY.FIL:");

getch();

flush(stream);

printf("\nFile was flushed, Press any key to quit:");

getch();

return 0;

}

void flush(FILE *stream)

{

int duphandle;

/* lam sach vung dem */

fflush(stream);

Page 6: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 6

duphandle = dup(fileno(stream));

close(duphandle);

}

Hàm fgetc Khai báo : Trích dẫn:

int fgetc(FILE *stream);

Hàm dùng lấy 1 ký tự từ tệp do con trỏ tệp stream trỏ đến . Nếu thành công hàm trả về mã ASCII của ký tự đọc được . Nếu gặp lỗi hay gặp kết thúc tệp thì hàm trả về EOF . Example

Code:

#include <string.h>

#include <stdio.h>

#include <conio.h>

int main(void)

{

FILE *stream;

char string[] = "This is a test";

char ch;

/* mo tep de ghi va doc */

stream = fopen("DUMMY.FIL", "w+");

/* ghi len tep mot chuoi */

fwrite(string, strlen(string), 1, stream);

/* dat con tro tep len dau tep */

fseek(stream, 0, SEEK_SET);

do

{

/* doc mot ky tu tu tep */

ch = fgetc(stream);

/* in ra man hinh ky tu doc duoc */

putch(ch);

} while (ch != EOF);

fclose(stream);

return 0;

}

Hàm fgetpos Khai báo : Trích dẫn:

Page 7: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 7

int fgetpos( FILE *stream,fpos_t *pos )

Hàm dùng lấy vị trí con trỏ tệp ( ở byte thứ mấy ) lưu vào trong biến pos . Nếu thành công hàm trả về 0 , ngược lại hàm trả về giá trị khác 0 . Example

Code:

#include <stdlib.h>

#include <stdio.h>

void showpos(FILE *stream);

int main(void)

{

FILE *stream;

fpos_t filepos;

/* mo file de doc ghi */

stream = fopen("DUMMY.FIL", "w+");

/* luu lai vi tri con tro tep hien thoi */

fgetpos(stream, &filepos);

/* ghi du lieu len tep */

fprintf(stream, "This is a test");

/* in ra man hinh vi tri con tro hien thoi */

showpos(stream);

/* dat lai vi tri con tro tep */

if (fsetpos(stream, &filepos) == 0)

showpos(stream);

else

{

fprintf(stderr, "Error setting file pointer.\n");

exit(1);

}

/* dong tep*/

fclose(stream);

return 0;

}

void showpos(FILE *stream)

{

fpos_t pos;

/* in ra man hinh vi tri con tro tep hien thoi */

fgetpos(stream, &pos);

printf("File position: %ld\n", pos);

}

Hàm fgets Khai báo : Trích dẫn:

Page 8: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 8

char *fgets(char *s,int n,FILE *fp);

Hàm dùng để đọc một chuỗi ký tự dài n-1 ký tự từ tệp fp vào chuỗi s . Việc đọc kết thúc khi đã đọc đủ n-1 ký tự hay gặp dấu xuống dòng hay gặp kết thúc tệp . Sau khi đọc , chuỗi s sẽ được tự động thêm vào ký tự NULL vào cuối chuỗi . Hàm trả về điạ chỉ chuỗi s nếu thành công , trái lại trả về NULL . Example Code:

#include <string.h>

#include <stdio.h>

int main(void)

{

FILE *stream;

char string[] = "This is a test";

char msg[20];

/* mo tep de doc ghi */

stream = fopen("DUMMY.FIL", "w+");

/* ghi mot chuoi vao tep */

fwrite(string, strlen(string), 1, stream);

/* dat con tro tep len dau tep */

fseek(stream, 0, SEEK_SET);

/* doc mot chuoi tu tep */

fgets(msg, strlen(string)+1, stream);

/* in chuoi ra man hinh */

printf("%s", msg);

fclose(stream);

return 0;

}

Hàm fopen Khai báo : Trích dẫn:

FILE *fopen(char *filename,char *type );

Hàm dùng để mở tệp . Với filename là chuỗi chứa tên tệp cần mở ( bao gồm cả đường dẫn cụ thể ) . Lưu ý một chút với filename này . Nếu bạn nhập chuỗi từ bàn phím thì khác với bạn đánh sẵn nó trong code của bạn . Ví dụ tệp ta cần mở tên là abc.jpg nằm ở ổ C . Đối với đánh tên tệp từ bàn phím thì ta đánh như sau : C:\abc.jpg . Nhưng nếu ta soạn sẵn trong code thì ta soạn như sau : C:\\abc.jpg ( tức là thêm 1 gạch \ ) . Kiểu mở tệp có rất nhiều cách nhưng chung quy ta có các trường hợp sau cho kiểu văn bản : "r" : đọc "w" : ghi "r+" hay "w+" : đọc và ghi "a" : ghi bổ sung "a+" : đọc ghi bổ sung

Page 9: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 9

Đối với mở file nhị phân bạn chỉ cần thêm chữ b vào sau các chuỗi trên . Nếu việc mở tệp thành công hàm cho địa chỉ con trỏ tệp , trái lại hàm trả về NULL . Example

Code:

#include <stdio.h>

int main(void)

{

FILE *in, *out;

if ((in = fopen("\\AUTOEXEC.BAT", "r"))

== NULL)

{

fprintf(stderr, "Cannot open input file.\n");

return 1;

}

if ((out = fopen("\\AUTOEXEC.BAK", "w"))

== NULL)

{

fprintf(stderr, "Cannot open output file.\n");

return 1;

}

while (!feof(in))

fputc(fgetc(in), out);

fclose(in);

fclose(out);

return 0;

}

Hàm fprintf Khai báo : Trích dẫn:

int fprintf(FILE *fp,char *s,...);

Hàm này chức năng y chang như hàm printf nhưng thay vì ghi ra màn hình thì nó ghi lên tệp fp . Nếu thành công hàm trả về số byte ghi được lên tệp , trái lại hàm trả về EOF . Example

Code:

#include <stdio.h>

int main(void)

{

FILE *stream;

int i = 100;

char c = 'C';

float f = 1.234;

Page 10: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 10

/* mo tep de doc ghi */

stream = fopen("DUMMY.FIL", "w+");

/* ghi du lieu len tep */

fprintf(stream, "%d %c %f", i, c, f);

/* dong tep */

fclose(stream);

return 0;

}

Hàm fputc Khai báo : Trích dẫn:

int fputc(int ch,FILE *fp);

Hàm ghi một ký tự có mã ASCII là ch lên tệp fp . khi thành công trả về mã ASCII của ký tự được ghi , trái lại hàm cho EOF . Example

Code:

#include <stdio.h>

int main(void)

{

char msg[] = "Hello world";

int i = 0;

while (msg[i])

{

fputc(msg[i], stdout);

i++;

}

return 0;

}

Hàm fputs Khai báo : Trích dẫn:

int fputs(char *s,FILE *fp);

Hàm ghi lên tệp fp chuỗi s . Chú ý rằng chuỗi s nên kết thúc bằng ký tự NULL , nếu ko việc ghi lên có thể bị sai lệch . Ký tự NULL này để chỉ ra vị trí kết thúc tệp cho rõ ràng chứ nó ko được ghi lên tệp . Hàm trả về ký tự cuối cùng được ghi lên tệp nếu thành công , trái lại hàm cho EOF . Example

Code:

Page 11: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 11

#include <stdio.h>

int main(void)

{

/* ghi mot chuoi ra dong xuat chuan ( man hinh ) */

fputs("Hello world\n", stdout);

return 0;

}

Hàm fread Khai báo : Trích dẫn:

int fread(void *ptr,int size,int n,FILE *fp);

Hàm đọc n mẫu tin , mỗi mẫu có kích thước size từ tệp fp lưu vào trong vùng nhớ ptr . Hàm trả về một giá trị bằng số mẫu tin thực sự đọc được . Nếu gặp lỗi hay gặp kết thúc tệp hàm trả về 0 . Example

Code:

#include <string.h>

#include <stdio.h>

int main(void)

{

FILE *stream;

char msg[] = "this is a test";

char buf[20];

if ((stream = fopen("DUMMY.FIL", "w+"))

== NULL)

{

fprintf(stderr, "Cannot open output file.\n");

return 1;

}

/* ghi du lieu len tep */

fwrite(msg, strlen(msg)+1, 1, stream);

/* dat con tro tep len dau tep */

fseek(stream, SEEK_SET, 0);

/* doc du lieu tu tep va xuat ra man hinh */

fread(buf, strlen(msg)+1, 1, stream);

printf("%s\n", buf);

fclose(stream);

return 0;

}

Page 12: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 12

Hàm freopen Khai báo : Trích dẫn:

FILE *freopen(char *filename,char *type,FILE *fp);

Hàm này có chức năng gán con trỏ tệp fp vào tệp filename . Sau đó có thể mở đọc ghi trên tệp này thông qua con trỏ tệp fp . Hàm này đặc biệt có ích khi ta muốn gán các con trỏ tệp chuẩn ( stdin , stdout , stderr ) vào 1 tệp của ta . Hàm trả về NULL nếu gặp lỗi . Example

Code:

#include <stdio.h>

int main(void)

{

/* gan con tro tep chuan stdout ( man hinh ) vao tep output.fil */

if (freopen("OUTPUT.FIL", "w", stdout)

== NULL)

fprintf(stderr, "error redirecting stdout\n");

/* khi do cau lenh nay se khong con xuat ra man hinh nua ma xuat vao

tep output.fil */

printf("This will go into a file.");

/*dong tep stdout lai */

fclose(stdout);

return 0;

}

Hàm fscanf Khai báo : Trích dẫn:

int fscanf(FILE *fp,char *s,...);

Hàm có chức năng đọc dữ liệu từ tệp . Làm việc giống như hàm scanf nhưng thay vì đọc từ màn hình thì hàm fscanf đọc từ tệp thôi . Hàm trả về 1 giá trị bằng số trường đọc được . Example

Code:

#include <stdlib.h>

#include <stdio.h>

int main(void)

{

int i;

printf("Input an integer: ");

/* doc mot so nguyen tu dong vao chuan */

Page 13: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 13

if (fscanf(stdin, "%d", &i))

printf("The integer read was: %i\n", i);

else

{

fprintf(stderr, "Error reading an integer from

stdin.\n");

exit(1);

}

return 0;

}

Hàm fseek Khai báo : Trích dẫn:

int fseek(FILE *fp,long sb,int xp);

Hàm dùng di chuyển con trỏ tệp fp đến vị trí bất kỳ . Với sb là số byte cần di chuyển , xp là vị trí xuất phát . Nếu sb dương tức là di chuyển về cuối tệp , nếu âm thì di chuyển về đầu tệp . Nếu xp là 0 hay SEEK_SET tức là xuất phát từ đầu tệp , nếu là SEEK_CUR hay 1 tức là xuất phát tại vị trí hiện thời của con trỏ tệp , nếu là SEEK_END hay 2 tức là xuất phát tại cuối tệp . Example

Code:

#include <stdio.h>

long filesize(FILE *stream);

int main(void)

{

FILE *stream;

stream = fopen("MYFILE.TXT", "w+");

fprintf(stream, "This is a test");

printf("Filesize of MYFILE.TXT is %ld bytes\n",

filesize(stream));

fclose(stream);

return 0;

}

long filesize(FILE *stream)

{

long curpos, length;

curpos = ftell(stream);

fseek(stream, 0L, SEEK_END);

length = ftell(stream);

fseek(stream, curpos, SEEK_SET);

return length;

}

Page 14: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 14

Hàm fsetpos Khai báo : Trích dẫn:

int fsetpos(FILE *stream , fpos_t pos);

Hàm này thường đi kèm cùng hàm fgetpos . Hàm dùng để di chuyển con trỏ tệp đến vị trí đươc lưu trong con trỏ pos . Vị trí này do hàm fgetpos lưu lại từ trước . Hàm trả về 0 nếu thành công , ngược lại trả về giá trị khác 0 . Example

Code:

#include <stdlib.h>

#include <stdio.h>

void showpos(FILE *stream);

int main(void)

{

FILE *stream;

fpos_t filepos;

/* mo file de doc ghi */

stream = fopen("DUMMY.FIL", "w+");

/* luu lai vi tri con tro tep hien thoi */

fgetpos(stream, &filepos);

/* ghi du lieu len tep */

fprintf(stream, "This is a test");

/* in ra man hinh vi tri con tro hien thoi */

showpos(stream);

/* dat lai vi tri con tro tep */

if (fsetpos(stream, &filepos) == 0)

showpos(stream);

else

{

fprintf(stderr, "Error setting file pointer.\n");

exit(1);

}

/* dong tep*/

fclose(stream);

return 0;

}

void showpos(FILE *stream)

{

fpos_t pos;

/* in ra man hinh vi tri con tro tep hien thoi */

fgetpos(stream, &pos);

printf("File position: %ld\n", pos);

Page 15: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 15

}

Hàm ftell Khai báo : Trích dẫn:

long ftell(FILE *fp);

Khi thành công hàm cho viết vị trí con trỏ tệp hiện thời đang ở vị trí thứ mấy ( tính từ đầu tệp ) , số hiệu của byte tính từ 0 . Ngược lại hàm trả về -1L . Nói thêm 1 tí về -1L có nghĩa là -1 mà lưu dưới dạng long ( dùng 4 byte để lưu ) . Example

Code:

int main(void)

{

FILE *stream;

stream = fopen("MYFILE.TXT", "w+");

fprintf(stream, "This is a test");

printf("The file pointer is at byte %ld\n",

ftell(stream));

fclose(stream);

return 0;

}

Hàm fwrite Khai báo : Trích dẫn:

int fwrite( void *ptr,int size,int n,FILE *fp );

Hàm dùng để ghi n mẫu tin kích thước size byte từ vùng nhớ ptr lên tệp fp . Hàm trả về 1 giá trị bằng số mẫu tin thực sự đọc được . Example

Code:

#include <stdio.h>

struct mystruct

{

int i;

char ch;

};

int main(void)

{

FILE *stream;

struct mystruct s;

Page 16: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 16

if ((stream = fopen("TEST.$$$", "wb")) == NULL) /* mo tep TEST.$$$

*/

{

fprintf(stderr, "Cannot open output file.\n");

return 1;

}

s.i = 0;

s.ch = 'A';

fwrite(&s, sizeof(s), 1, stream); /* viết cấu trúc s lên tep */

fclose(stream); /* dong tep */

return 0;

}

2. String & Character

Danh sách các hàm với String & Character 1.atof 2.atoi 3.atol 4.isalnum 5.isalpha 6.iscntrl 7.isdigit 8.isgraph 9.islower 10.isprint 11.ispunct 12.isspace 13.isupper 14.isxdigit 15.memchr 16.memcmp 17.memcpy 18.memmove

Page 17: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 17

19.memset 20.strcat 21.strchr 22.strcmp 23.strcoll 24.strcpy 25.strcspn 26.strerror 27.strlen 28.strncat 29.strncmp 30.strncpy 31.strpbrk 32.strrchr 33.strspn 34.strstr 35.strtod 36.strtok 37.strtol 38.strtoul 39.strxfrm 40.tolower 41.toupper

1. atof() Tên hàm: atof() Định nghĩa: PHP Code:

Page 18: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 18

#include <stdlib.h>

double atof( const char *str );

Chuỗi 'str' phải bắt đầu bằng kí tự số, nếu không sẽ bị lỗi chương trình (termination) Ví dụ về 3 trường hợp PHP Code: #include <stdio.h>

#include <stdlib.h>

int main(void)

{

char *strA="30.4";

char *strB="17.3 thu xem dc khong?";

char *strC="Cai nay chac co loi 33.4";

double a,b,c;

a = atof(strA);

b = atof(strB);

//c = atof(strC); <--- Dong nay convert se bi loi

printf("\nGia tri cua chuoi %s sau khi convert la %.2f",strA,a);

printf("\nGia tri cua chuoi %s sau khi convert la %.2f",strB,b);

//printf("\nGia tri cua chuoi %s sau khi convert la %.2f",strC,c);

<--- bo comment ra se co loi

return 0;

}

2. atoi()

Tên hàm: atoi() Định nghĩa: PHP Code: #include <cstdlib>

int atoi( const char *str );

'str' phải bắt đầu bằng số hoặc kí tự trắng <space> nếu không convert sẽ fail và trả về 0. Code minh họa PHP Code: #include <stdio.h>

#include <stdlib.h>

int main(void)

{

int i;

i = atoi( "512" );

printf("\nGia tri cua i la: %d",i);

i = atoi( "512.035" );

printf("\nGia tri cua i la: %d",i);

i = atoi( " 512.035" );

printf("\nGia tri cua i la: %d",i);

i = atoi( " 512+34" );

printf("\nGia tri cua i la: %d",i);

Page 19: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 19

i = atoi( " 512 bottles of beer on the wall" );

printf("\nGia tri cua i la: %d",i);

// Truong hop duoi day se in ra 0

i = atoi(" that bai 512 ");

printf("\nGia tri cua i la: %d",i);

return 0;

}

3. atol()

Tên hàm: atol() Định nghĩa: PHP Code: #include <stdlib.h>

long atol( const char *str );

Tương tự như atoi() Minh họa PHP Code: #include <stdio.h>

#include <stdlib.h>

int main(void)

{

int i;

i = atol( "512" );

printf("\nGia tri cua i la: %d",i);

i = atol( "512.035" );

printf("\nGia tri cua i la: %d",i);

i = atol( " 512.035" );

printf("\nGia tri cua i la: %d",i);

i = atol( " 512+34" );

printf("\nGia tri cua i la: %d",i);

i = atol( " 512 bottles of beer on the wall" );

printf("\nGia tri cua i la: %d",i);

// Truong hop duoi day se in ra 0

i = atol(" that bai 512 ");

printf("\nGia tri cua i la: %d",i);

return 0;

} 4. isalnum() Tên hàm: isalnum() Định nghĩa: PHP Code: #include <ctype.h>

int isalnum( int ch );

Kiểm tra một kí tự là số hay chữ cái. Nếu đúng trả về giá trị khác 0 Nếu sai trả về 0

PHP Code: #include <stdio.h>

#include <ctype.h>

Page 20: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 20

int main(void)

{

char x='X';

if(isalnum(x)) {

printf("Day la ki tu %c",x);

} else {

printf("Ki tu %c ko phai la so hoac chu",x);

}

return 0;

}

5.isalpha()

Tên hàm: isalpha() Định nghĩa: PHP Code: #include <ctype.h>

int isalpha( int ch );

Kiểm tra một kí tự có phải là chữ cái hay không. Đúng thì trả về khác 0 Sai thì trả về 0

PHP Code: #include <stdio.h>

#include <ctype.h>

int main(void)

{

char x='0';

if(isalpha(x)) {

printf("Day la ki tu chu cai %c",x);

} else {

printf("Ki tu %c ko phai la chu cai",x);

}

return 0;

}

6. iscntrl()

Tên hàm: iscntrl() Định nghĩa: PHP Code: #include <ctype.h>

int iscntrl( int ch );

Kiểm tra một kí tự có thuộc nhóm kí tự điều khiển hay không Nhóm kí tự điều khiển (Control Character) nằm từ : 0x00 đến 0x1F và kí tự 0x7F Đúng thì trả về khác 0 Sai thì trả về 0

Page 21: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 21

Xem bảng kí tự ở đây:

PHP Code: #include <stdio.h>

#include <ctype.h>

int main(void)

{

char x='\x7F';

if(iscntrl(x)) {

printf("Day la ki tu dieu khien ",x);

} else {

printf("Ki tu nay ko thuoc nhom ki tu dieu khien",x);

}

return 0;

}

7. isdigit()

Tên hàm: isdigit() Định nghĩa:

Page 22: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 22

PHP Code: #include <ctype.h>

int isdigit( int ch );

Kiểm tra 1 kí tự có phải là kí tự số hay không Đúng thì trả về khác 0 Sai thì trả về 0

PHP Code: #include <stdio.h>

#include <ctype.h>

int main(void)

{

char x='7';

if(isdigit(x)) {

printf("Ki tu %c la ki tu so",x);

} else {

printf("Ki tu %c ko phai ki tu so",x);

}

return 0;

}

8. isgraph()

Tên hàm: isgraph() Định nghĩa: PHP Code: #include <ctype.h>

int isgraph( int ch );

Bất cứ kí tự nào có thể in ra được (printable character) đều gọi là Graphical Character, ngoại trừ kí tự <space> Kiểm tra xem kí tự có thuộc nhóm graph không Đúng thì trả về khác 0 Sai thì trả về 0

PHP Code: #include <stdio.h>

#include <ctype.h>

int main(void)

{

char x='t';

if(isgraph(x)) {

printf("Ki tu %c thuoc nhom graphical char",x);

} else {

printf("Ki tu %c ko thuoc nhom graphical char",x);

}

return 0;

}

9. islower()

Page 23: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 23

Tên hàm: islower() Định nghĩa PHP Code: #include <ctype.h>

int islower( int ch );

Kiểm tra một kí tự xem có phải chữ in thường không Đúng thì trả về khác 0 Sai thì trả về 0

PHP Code: #include <stdio.h>

#include <ctype.h>

int main(void)

{

char x='K';

if(islower(x)) {

printf("Ki tu %c la chu in thuong",x);

} else {

printf("Ki tu %c ko phai chu in thuong",x);

}

return 0;

}

10. isprint()

Tên hàm: isprint() Định nghĩa: PHP Code: #include <ctype.h>

int isprint( int ch );

Printable character bao gồm Graphical Character và kí tự trắng <space> kiểm tra 1 kí tự có phải là printable character hay không Đúng thì trả về khác 0 Sai thì trả về 0

PHP Code: #include <stdio.h>

#include <ctype.h>

int main(void)

{

char x='\x7F';

if(isprint(x)) {

printf("Ki tu %c la printable char",x);

} else {

printf("Ki tu %c ko phai printable char",x);

}

return 0;

} 11. ispunct()

Page 24: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 24

Tên hàm: ispunct() Định nghĩa: PHP Code: #include <ctype.h>

int ispunct( int ch );

Punctuation Character là các kí tự trong nhóm Graphical Character nhưng không phải là chữ cái hay số Đúng thì trả về khác 0 Sai thì trả về 0

PHP Code: #include <stdio.h>

#include <ctype.h>

int main(void)

{

char x='\'';

if(ispunct(x)) {

printf("Ki tu %c la punct char",x);

} else {

printf("Ki tu %c ko phai punct char",x);

}

return 0;

}

12. isspace()

Tên hàm: isspace() Định nghĩa: PHP Code: #include <ctype.h>

int isspace( int ch );

Space Character là những kí tự tạo nên khoảng trắng (line feed, form feed...) Đúng thì trả về khác 0 Sai thì trả về 0

PHP Code: #include <stdio.h>

#include <ctype.h>

int main(void)

{

char x='\x0B';

if(isspace(x)) {

printf("Ki tu %c la space char",x);

} else {

printf("Ki tu %c ko phai space char",x);

}

return 0;

}

Page 25: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 25

13. isupper()

Tên hàm: isupper() Định nghĩa: PHP Code: #include <ctype.h>

int isupper( int ch );

Kiểm tra một kí tự có phải chữ in Hoa hay không Đúng thì trả về khác 0 Sai thì trả vè 0

PHP Code: #include <stdio.h>

#include <ctype.h>

int main(void)

{

char x='x';

if(isupper(x)) {

printf("Ki tu %c la chu in hoa",x);

} else {

printf("Ki tu %c ko phai chu in hoa",x);

}

return 0;

}

14. isxdigit()

Tên hàm: isxdigit() Định nghĩa: PHP Code: #include <ctype.h>

int isxdigit( int ch );

Kiểm tra xem một kí tự có phải là số ở hệ thập lục (Hex - 16) hay không Đúng thì trả về khác 0 Sai thì trả về 0

PHP Code: #include <stdio.h>

#include <ctype.h>

int main(void)

{

char x='B';

if(isxdigit(x)) {

printf("Ki tu %c la hex char",x);

} else {

printf("Ki tu %c ko phai hex char",x);

}

return 0;

} 15. memchr()

Page 26: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 26

Tên hàm: memchr() Định nghĩa: PHP Code: #include <string.h>

void *memchr( const void *buffer, int ch, size_t count );

Tìm vị trí xuất hiện đầu tiên của kí tự 'ch' trong buffer của một chuỗi 'buffer' trong khoảng kí tự giới hạn 'count' cho trước. Nếu tìm thấy thì trả về vị trí kí tự xuất hiện trong chuỗi 'buffer' Ngược lại NULL trả về

PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

{

char buffer[]="Xcross87 is a chick of programming";

char x='X';

int found = memchr(buffer,x,strlen(buffer));

if(found) {

printf(" Tim thay %c ",x);

} else {

printf(" Khong tim thay ki tu %c ",x);

}

return 0;

} 16. memcmp()

Tên hàm: memcmp() Định nghĩa: PHP Code: #include <string.h>

int memcmp( const void *buffer1, const void *buffer2, size_t count );

So sánh 'count' kí tự đầu tiên của 2 chuỗi buffer1 và buffer2 Giá trị trả về: PHP Code: Nhỏ hơn 0 : buffer1 < buffer2

= 0 : buffer1=buffer2

Lớn hơn 0 : buffer1 > buffer2

PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

{

char buffer1[]="Xcross87 is a chick of programming";

char buffer2[]="Xcross87 is a crazy";

Page 27: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 27

int compare_result = memcmp(buffer1,buffer2,strlen(buffer2));

if(compare_result < 0) {

printf(" buffer1 < buffer2 ");

} else if (compare_result == 0) {

printf(" buffer1 = buffer2 ");

} else {

printf(" buffer1 > buffer2 ");

}

return 0;

} 17. memcpy()

Tên hàm: memcpy() Định nghĩa: PHP Code: #include <string.h>

void *memcpy( void *to, const void *from, size_t count );

Copy 'count' kí tự từ 'from' sang 'to'. Giá trị trả về là 'to' Chú ý: hàm này sẽ copy nguyên chính xác số bytes cần copy và không copy bytes cuối cùng của string '\0'. Vì vậy cần phải copy n+1 nếu muốn copy n byte

PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

{

const char from[]="Xcross87 is a chick of programming";

char* to;

memcpy(to,from,strlen(from)+1);

printf(" Gia tri cua \'to\' sau khi copy la: %s ",to);

return 0;

} 18. memmove()

Tên hàm: memmove() Định nghĩa: PHP Code: #include <string.h>

void *memmove( void *to, const void *from, size_t count );

Giống hàm memcpy() nhưng xử lý được tình huống overlap với from và to. Chú ý: nên sử dụng memmove() thay vì sử dụng memcpy()

PHP Code:

Page 28: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 28

#include <stdio.h>

#include <string.h>

int main(void)

{

const char from[]="Xcross87 is a chick of programming";

char* to;

memmove(to,from,strlen(from));

printf("\n Gia tri cua \'to\' sau khi move la: %s ",to);

return 0;

} 19. memset()

Tên hàm: memset() Định nghĩa: PHP Code: #include <string.h>

void* memset( void* buffer, int ch, size_t count );

Lấp đầy 'count' bytes đầu tiên trong 'buffer' với kí tự 'ch' Hàm chuyên sử dụng để lấp đầy hoặc khởi tạo memory block hay array, tốc độ xử lý tốt hơn vòng lặp. PHP Code: #include <stdio.h>

#include <string.h>

#define LENGTH 10

int main(void)

{

char x='X';

char buffer[LENGTH];

int cnt=0;

memset(buffer,x,LENGTH);

for(;cnt < LENGTH; cnt++) {

printf("\nbuffer[%d] = %c",cnt,buffer[cnt]);

}

return 0;

} 20. strcat()

Tên hàm: strcat() Định nghĩa: PHP Code: #include <string.h>

char *strcat( char *str1, const char *str2 );

Nối 'str2' vào 'str1' và trả về 'str1' Chú ý: Hàm dễ xảy ra overflow, copy quá giới hạn cho phép (over bound)

PHP Code:

Page 29: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 29

#include <stdio.h>

#include <string.h>

int main(void)

{

char *str1="Xcross87 ";

char *str2="is a crazy";

str1 = strcat(str1,str2);

printf(" Sau khi noi chuoi: %s ",str1);

return 0;

} 21. strchr()

tên hàm: strchr() Định nghĩa: PHP Code: #include <string.h>

char *strchr( const char *str, int ch );

Hàm trả về giá trị chuỗi bắt đầu với 'ch' trong chuỗi 'str'. Trả về NULL nếu không tìm thấy gì hết. ví dụ dưới đây sẽ cho ra kết quả là : 'ss87' PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

{

const char *str="Xcross87 ";

char* found;

found = strchr(str,'s');

if ( NULL == found ) {

printf(" Not found ");

} else {

printf(" Found %s ",found);

}

return 0;

}

22. strcmp()

tên hàm: strcmp() Định nghĩa: PHP Code: #include <string.h>

int strcmp( const char *str1, const char *str2 );

So sánh 2 chuỗi 'str1' và 'str2' Giá trị trả về ;

Page 30: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 30

PHP Code: < 0 : str1 < str2

= 0 : str1 = str2

> 0 : str1 > str2

PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

{

const char *str1="Xcross87 ";

const char *str2="Xcross";

int result = strcmp(str1,str2);

if(result < 0) {

printf(" str1 < str2 ");

} else if (result == 0) {

printf(" str1 = str2 ");

} else {

printf(" str1 > str2 ");

}

return 0;

}

23. strcoll()

tên hàm: strcoll() Định nghĩa: PHP Code: #include <cstring>

int strcoll( const char *str1, const char *str2 ); 24. strcpy()

tên hàm: strcpy() định nghĩa: PHP Code: #include <string.h>

char *strcpy( char *to, const char *from );

Copy từ chuỗi 'from' sang chuỗi 'to' Chú ý: hàm dễ xảy ra buffer overflow

PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

{

const char *from="Xcross87 ";

char *to;

Page 31: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 31

to = strcpy(to,from);

printf("sau khi copy: %s",to);

return 0;

}

25. strcspn()

tên hàm: strcspn() định nghĩa: PHP Code: #include <string.h>

size_t strcspn( const char *str1, const char *str2 );

Trả về vị trí đầu tiên của bất cứ kí tự nào trong 'str1' tìm thấy trong 'str2' Nếu không tìm thấy thì trả về độ dài chuỗi str1

PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

{

const char *str="Xcross87 ";

char *key="123456789";

int pos = strcspn(str,key);

printf("tim thay o vi tri %d",pos);

return 0;

}

26. strerror()

tên hàm: strerror() định nghĩa: PHP Code: #include <string.h>

char *strerror( int num );

Lấy chuỗi error báo lỗi tương ứng của lỗi tìm được Ví dụ dưới đây minh họa báo lỗi không tìm thấy file

PHP Code: #include <stdio.h>

#include <string.h>

#include <errno.h>

int main(void)

Page 32: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 32

{

FILE* pfile;

pfile = fopen("file_name.o","r");

if (NULL == pfile) {

printf("%s",strerror(errno));

}

return 0;

}

27. strlen()

tên hàm: strlen() định nghĩa: PHP Code: #include <string.h>

size_t strlen( char *str );

Hàm trả về độ dài của chuỗi

PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

{

const char *str="congdongcviet.com";

printf("do dai chuoi la: %d",strlen(str));

return 0;

}

28. strncat()

tên hàm: strncat() định nghĩa: PHP Code: #include <string.h>

char *strncat( char *str1, const char *str2, size_t count );

Nối chuôi cơ ban như hàm strcat() nhưng chỉ định số byte của chuỗi str2 để nối vào str1 PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

{

const char *str1="con ga";

const char *str2=" xcross87 is crazy";

char *result;

result = strncat(str1,str2,9);

Page 33: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 33

printf("Chuoi sau khi noi: %s",result);

return 0;

}

29. strncmp()

tên hàm: strncmp() định nghĩa: PHP Code: #include <string.h>

int strncmp( const char *str1, const char *str2, size_t count );

Giống hàm strcmp() nhưng chỉ so sánh 'count' bytes cho trước.

30. strncpy()

tên hàm: strncpy() định nghĩa: PHP Code: #include <string.h>

char *strncpy( char *to, const char *from, size_t count );

Copy từ from vào to với số byte quy định

31. strpbrk()

tên hàm: strpbrk() định nghĩa: PHP Code: #include <string.h>

char* strpbrk( const char* str1, const char* str2 );

trả về kí tự xuất hiện đầu tiên trong 'str1' xuất hiện trong 'str2'. Trả về NULL nếu không tìm thấy.

PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

{

const char *str1="con ga trong ko phai la con ga mai";

const char *str2="zzzzzzzzzzzza";

char* found;

found = strpbrk(str1,str2);

if (NULL != found) {

printf(" Tim thay ki tu dau tien: %c ",*found);

}

return 0;

}

Page 34: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 34

32. strpbrk()

tên hàm: strpbrk() định nghĩa: PHP Code: #include <string.h>

char* strpbrk( const char* str1, const char* str2 );

trả về kí tự xuất hiện đầu tiên trong 'str1' xuất hiện trong 'str2'. Trả về NULL nếu không tìm thấy.

PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

{

const char *str1="con ga trong ko phai la con ga mai";

const char *str2="zzzzzzzzzzzza";

char* found;

found = strpbrk(str1,str2);

if (NULL != found) {

printf(" Tim thay ki tu dau tien: %c ",*found);

}

return 0;

}

33. strrchr

tên hàm: strrchr() định nghĩa: PHP Code: #include <string.h>

char *strrchr( const char *str, int ch );

Trả về sự xuất hiện cuối cùng của kí tự 'ch' trong chuỗi 'str' 35. strstr(0

tên hàm: strstr() định nghĩa: PHP Code: #include <string.h>

size_t strspn( const char *str1, const char *str2 );

trả về con trỏ tới vị trí đầu tiên của str2 trong str1 nếu tìm thấy trả về NULL nếu không thấy nếu độ dài của str2 là 0 thì trả về độ dài của str1.

PHP Code: #include <stdio.h>

#include <string.h>

int main(void)

Page 35: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 35

{

const char *str1="con ga trong ko phai la con ga mai";

const char *str2="la";

char* result;

result = strstr(str1,str2);

if(NULL != result) {

printf(" Doan tim thay: %s", result);

}

return 0;

} 36. strtod()

tên hàm: strtod() định nghĩa: PHP Code: #include <stdlib.h>

double strtod( const char *start, char **end );

start là chuỗi đầu vào của convert; end là phần còn lại của chuỗi sau khi convert. convert thành công thì trả về số double đã convert nếu thất bại thì trả về: 0.0 nếu convert thành công mà kết quả lại quá to so với giới hạn của double thì HUGE_VAL được trả về và errno=ERANGE nếu underflow thì trả về 0.0 và errno=ERANGE

PHP Code: #include <stdio.h>

#include <stdlib.h>

int main ()

{

char *start="12.3 xcross87 in congdongcviet.com";

char *end;

double result;

result = strtod(start,&end);

printf("Sau khi convert: ");

printf("\n start = %s ",start);

printf("\n end = %s ",end);

printf("\n result = %lf",result);

return 0;

} 37. strtok()

tên hàm: strtok() định nghĩa: PHP Code:

Page 36: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 36

#include <string.h>

char *strtok( char *str1, const char *str2 );

trả về chuỗi đầu tiên được cưa ra trong str1 theo khóa str2. nếu không tìm thấy thì trả về NULL. sau khi kết thúc toàn bộ token trong str1 thì str1=NULL

PHP Code: #include <stdio.h>

#include <string.h>

int main ()

{

char *str1="xcross87 | xcross87.info | hcegroup.net | congdongcviet

.com";

const char *str2="|";

char *token = NULL;

// token lan 1

token = strtok(str1,str2);

printf("\nstr1 = %s",str1);

printf("\nstr2 = %s",str2);

printf("\ntoken = %s\n",token);

// token lan 2

token = strtok(NULL,str2);

printf("\nstr1 = %s",str1);

printf("\nstr2 = %s",str2);

printf("\ntoken = %s\n",token);

return 0;

} 38. strtol()

tên hàm: strtol() định nghĩa: PHP Code: #include <stdlib.h>

long strtol( const char *start, char **end, int base );

tương tự strtod() nhưng chuỗi vào start có base cho trước để convert sang. 39. strtoul()

tên hàm: strtoul() định nghĩa: PHP Code: #include <stdlib.h>

unsigned long strtoul( const char *start, char **end, int base );

giống như strtol() nhưng cho kiểu unsigned long

Page 37: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 37

40. strxfrm()

tên hàm: strxfrm() định nghĩa: PHP Code: #include <string.h>

size_t strxfrm( char *str1, const char *str2, size_t num );

copy 'num' bytes từ str2 sang str1

41. tolower()

tên hàm: tolower() định nghĩa: PHP Code: #include <ctype.h>

int tolower( int ch );

convert sang kí tự thường

PHP Code: #include <stdio.h>

#include <ctype.h>

int main ()

{

char x='X';

x = tolower(x);

printf("sau khi convert: %c",x);

return 0;

} 42. toupper()

tên hàm: toupper() định nghĩa: PHP Code: #include <ctype.h>

int toupper( int ch );

convert kí tự sang kí tự hoa

PHP Code: #include <stdio.h>

#include <ctype.h>

int main ()

{

char x='x';

x = toupper(x);

printf("sau khi convert: %c",x);

Page 38: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 38

return 0;

} 3. Math

Các hàm làm việc liên quan đên MATH 1.abs 2.acos 3.asin 4.tan 5.atan2 6.ceil 7.cos 8.cosh 9.div 10.exp 11.fabs 12.floor 13.fmod 14.frexp 15.labs 16.ldexp 17.ldiv 19.log 20.log10 21.modf 22.pow 23.sin 24.sinh 25.sqrt 26.tan

Page 39: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 39

27.tanh 1. abs()

tên hàm: abs() định nghĩa: PHP Code: #include <stdlib.h>

int abs( int num );

trả về giá trị tuyệt đối của 1 số

PHP Code: #include <stdio.h>

#include <stdlib.h>

int main(void)

{

int x=-10;

printf("Gia tri tuyet doi cua %d la %d",x,abs(x));

return 0;

} 2. acos()

tên hàm: acos() định nghĩa: PHP Code: #include <math.h>

double acos( double arg );

trả về giá trị arc cosine của 'arg' trong khoảng [0,PI], arg nằm trong khoảng [-1,1]. Nếu arg ngoài giới hạn cho phép thì acos() trả về giá trị NAN

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x=-1;

printf("acos(%.2lf) = %.2lf",x,acos(x));

return 0;

} 3. asin()

tên hàm: asin() định nghĩa: PHP Code: #include <math.h>

double asin( double arg );

hàm trả về arc sine của arg

Page 40: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 40

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x=0;

printf("asin(%.2lf) = %.2lf",x,asin(x));

return 0;

} 4. atan()

tên hàm: atan() định nghĩa: PHP Code: #include <math.h>

double atan( double arg );

Hàm trả về arc tangent của một số

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x=0;

printf("atan(%.2lf) = %.2lf",x,atan(x));

return 0;

} 5. atan2()

tên hàm: atan2() định nghĩa: PHP Code: #include <math.h>

double atan2( double y, double x );

trả về arc tangent của y/x

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double y=0;

double x=100;

printf("atan2(%.2lf/%.2lf) = %.2lf",y,x,atan(y/x));

return 0;

} 7. ceil()

Page 41: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 41

tên hàm: ceil() định nghĩa: PHP Code: #include <math.h>

double ceil( double num );

trả về giá trị trần của một số

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x = 1.3;

printf("ceil(%.2lf) = %.2lf",x,ceil(x));

return 0;

} 8. cos()

tên hàm: cos() định nghĩa: PHP Code: #include <math.h>

double cos( double arg );

trả về giá trị cosine của một số

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x = 0;

printf("cos(%.2lf) = %.2lf",x,cos(x));

return 0;

} 9. cosh()

tên hàm: cosh() định nghĩa: PHP Code: #include <math.h>

double cosh( double arg );

trả về giá trị hyperbolic cosine của một số

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

Page 42: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 42

double x = 0;

printf("cosh(%.2lf) = %.2lf",x,cosh(x));

return 0;

} 10.div()

tên hàm: div() định nghĩa: PHP Code: #include <stdlib.h>

div_t div( int numerator, int denominator );

trả về phần nguyên và phần dư của một phép chia

PHP Code: #include <stdio.h>

#include <stdlib.h>

int main(void)

{

int x = 17;

int y = 4;

div_t result;

result = div(x,y);

printf("Phan nguyen: %d || Phan du: %d ",result.quot,result.rem);

return 0;

} 11. exp()

tên hàm: exp() định nghĩa: PHP Code: #include <math.h>

double exp( double arg );

trả về lũy thừa của e

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x = 2;

printf("e^2 = %.2lf",exp(x));

return 0;

} 12. fabs()

tên hàm: fabs() định nghĩa: PHP Code:

Page 43: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 43

#include <math.h>

double fabs( double arg );

trả về giá trị tuyệt đối của số thực

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x = -2.2;

printf("|-2.2| = %.2lf",fabs(x));

return 0;

} 13. floor()

tên hàm: floor() định nghĩa: PHP Code: #include <math.h>

double floor( double arg );

trả về giá trị sàn của một số

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x = -2.2;

printf("floor(%.2lf) = %.2lf",x,floor(x));

return 0;

} 14. fmod()

tên hàm: fmod() định nghĩa: PHP Code: #include <math.h>

double fmod( double x, double y );

trả về phần dư của phép chia: x/y

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x = 2.2;

double y = 1.1;

Page 44: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 44

printf("%.2lf/%.2lf du %.2lf",x,y,fmod(x,y));

return 0;

} 15. frexp()

tên hàm: frexp() định nghĩa: PHP Code: #include <math.h>

double frexp( double num, int* exp );

hàm này dùng với phương trình: num = result * ( 2 ^ exp ); hàm trả về result:

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x = 2.2;

int exp;

double result;

result = frexp(x,&exp);

printf(" %f = %f * ( 2 ^ %d ) ", x, result,exp);

return 0;

} 16. labs()

tên hàm: labs() định nghĩa: PHP Code: #include <stdlib.h>

long labs( long num );

trả về giá trị tuyệt đối của một số kiểu long integer PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

long x = -3333333;

printf(" |%ld| = %ld " , x , labs(x));

return 0;

} 17. ldexp()

tên hàm: ldexp() định nghĩa: PHP Code:

Page 45: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 45

#include <math.h>

double ldexp( double num, int exp );

hàm trả về giá trị của phép toán: num * (2 ^ exp)

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double num = 3.2;

int exp = 2;

printf(" Ket qua la : %.2lf ", ldexp(num,exp));

return 0;

} 18. ldiv()

tên hàm: ldiv() định nghĩa: PHP Code: #include <stdlib.h>

ldiv_t ldiv( long numerator, long denominator );

trả về phần nguyên và dư của số kiểu long

PHP Code: #include <stdio.h>

#include <stdlib.h>

int main(void)

{

long x = 30;

long y = 17;

ldiv_t result = ldiv(x,y);

printf(" Phan nguyen = %ld || Phan du = %ld ",result.quot, result.r

em);

return 0;

} 19. log()

tên hàm: log() định nghĩa: PHP Code: #include <math.h>

double log( double num );

trả về logarit tự nhiên của num

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

Page 46: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 46

{

double num = 2;

printf(" log(%.2lf) = %.2lf " , num, log(num));

return 0;

} 20. log10()

tên hàm: log10() định nghĩa: PHP Code: #include <math.h>

double log10( double num );

trả về logarit cơ số 10 của num

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double num = 2;

printf(" log10(%.2lf) = %.2lf " , num, log10(num));

return 0;

}

21. modf()

tên hàm: modf() định nghĩa: PHP Code: #include <math.h>

double modf( double num, double *i );

tách phần nguyên và thập phân của một sô thập phân hàm trả về phần thập phân

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double num = 1.17;

double intpart;

double fractpart = modf(num,&intpart);

printf(" %lf = %lf + %lf " , num,intpart,fractpart);

return 0;

} 22. pow()

Page 47: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 47

tên hàm: pow() định nghĩa: PHP Code: #include <math.h>

double pow( double base, double exp );

tính lũy thừa của một số

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double base = 2;

double exp = 3;

printf(" %lf^%lf = %lf ", base,exp,pow(base,exp));

return 0;

} 23. sin()

tên hàm: sin() định nghĩa: PHP Code: #include <math.h>

double sin( double arg );

trả về sin của 'arg'

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x = 0;

printf(" sin(%.1lf) = %lf ",x,sin(x));

return 0;

} 24. sinh()

tên hàm: sinh() định nghĩa: PHP Code: #include <math.h>

double sinh( double arg );

trả về hyperbolic sine của 'arg'

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

Page 48: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 48

{

double x = 0;

printf(" sinh(%.1lf) = %lf ",x,sinh(x));

return 0;

} 25. sqrt()

tên hàm: sqrt() định nghĩa: PHP Code: #include <math.h>

double sqrt( double num );

trả về căn bậc 2 của một số PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x = 4;

printf(" sqrt(%.1lf) = %lf ",x,sqrt(x));

return 0;

} 26. tan()

tên hàm: tan() định nghĩa: PHP Code: #include <math.h>

double tan( double arg );

trả về tangent của 'arg'

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x = 4;

printf(" tan(%.1lf) = %lf ",x,tan(x));

return 0;

} 27. tanh()

tên hàm: tanh() định nghĩa: PHP Code: #include <math.h>

double tanh( double arg );

trả về hyperbolic tangent của 'arg'

Page 49: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 49

PHP Code: #include <stdio.h>

#include <math.h>

int main(void)

{

double x = 4;

printf(" tanh(%.1lf) = %lf ",x,tanh(x));

return 0;

} 4. Date & Time

Các hàm xử lý Date & time 1.asctime 2.clock 3.ctime 4.difftime 5.gmtime 6.localtime 7.mktime 8.setlocale 9.strftime 10.time 1. asctime()

tên hàm: asctime() định nghĩa: PHP Code: #include <time.h>

char *asctime( const struct tm *ptr );

convert cấu trúc 'ptr'(pointer to time struct) thành chuỗi thời gian có dạng Code:

day month date hours:minutes:seconds year

ví dụ: Code:

Mon Jun 26 12:03:53 2000

ví dụ PHP Code: #include <stdio.h>

#include <time.h>

Page 50: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 50

int main(void)

{

time_t rawtime;

struct tm *timeinfo;

time(&rawtime);

timeinfo = localtime(&rawtime);

printf("The current date/time is: %s",asctime(timeinfo));

return 0;

} 2. clock()

tên hàm: clock() định nghĩa: PHP Code: #include <ctime>

clock_t clock( void );

trả về số tick đồng hồ kể từ khi bắt đầu chương trình ví dụ PHP Code: #include <stdio.h>

#include <time.h>

void wait(int sec)

{

clock_t endwait;

endwait = clock() + sec * CLOCKS_PER_SEC;

while(clock() < endwait) {}

}

int main(void)

{

int cnt = 0;

printf("I'm sleeping for 5 seconds...\n");

for(; cnt < 5; cnt++) {

printf("%d\n",cnt);

wait(1);

}

printf("Wake up NOW !");

return 0;

} 3. ctime()

tên hàm: ctime() định nghĩa: PHP Code: #include <time.h>

char *ctime( const time_t *time );

lấy thời gian dưới dạng PHP Code:

Page 51: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 51

day month date hours:minutes:seconds year

tương đương với asctime(localtime(&timeptr)) ví dụ PHP Code: #include <stdio.h>

#include <time.h>

int main(void)

{

time_t rawtime;

time(&rawtime);

printf("Time now is: %s",ctime(&rawtime));

return 0;

} 4. difftime()

tên hàm: difftime() định nghĩa: PHP Code: #include <time.h>

double difftime( time_t time2, time_t time1 );

Trả về số giây so sánh bằng giây 5. gmtime()

tên hàm: gmtime() định nghĩa: PHP Code: #include <time.h>

struct tm *gmtime( const time_t *time );

trả về pointer tới GMT ví dụ lấy giờ Hà Nội GMT +7 [ICT]

PHP Code: #include <stdio.h>

#include <time.h>

#define ICT (+7)

int main(void)

{

struct tm *gmt;

time_t raw;

time(&raw);

gmt = gmtime(&raw);

printf("GMT +7:00 | %2d:%2d ",(gmt->tm_hour+ICT)%24,gmt-

>tm_min);

Page 52: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 52

return 0;

} 6. localtime()

tên hàm: localtime() định nghĩa: PHP Code: #include <time.h>

struct tm *localtime( const time_t *time );

trả về local time

PHP Code: #include <stdio.h>

#include <time.h>

int main(void)

{

time_t rawtime;

struct tm *local;

time(&rawtime);

local = localtime(&rawtime);

printf("Local time: %s",asctime(local));

return 0;

} 7. mktime()

tên hàm: mktime() định nghĩa: PHP Code: #include <time.h>

time_t mktime( struct tm *time );

trả về calendar time tương ứng với localtime, nếu thất bại thì trả về -1

ví dụ: kiểm tra xem ngày 17 tháng 1 năm 1987 là thứ mấy

PHP Code: #include <stdio.h>

#include <time.h>

int main(void)

{

time_t rawtime;

struct tm *info;

char *weekday[] = { "Sunday", "Monday",

"Tuesday", "Wednesday",

"Thursday", "Friday", "Saturday"};

time(&rawtime);

info = localtime(&rawtime);

info->tm_year = 1987 - 1900;

Page 53: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 53

info->tm_mon = 1;

info->tm_mday = 17;

mktime(info);

printf("That weekday is %s", weekday[info->tm_wday]);

return 0;

} 8.setlocale 8. strftime()

tên hàm: strftime() định nghĩa: PHP Code: #include <time.h>

size_t strftime( char *str, size_t maxsize, const char *fmt, struct tm

*time );

convert time format từ time sang str với kiểu format 'fmt' và buffer size 'maxsize' ví dụ lấy thời gian hiện tại PHP Code: #include <stdio.h>

#include <time.h>

int main(void)

{

time_t rawtime;

struct tm *now;

char buffer[80];

time(&rawtime);

now = localtime(&rawtime);

strftime(buffer,80,"time now is %I:%M %p",now);

puts(buffer);

return 0;

}

9. time()

tên hàm: time() định nghĩa: PHP Code: #include <time.h>

time_t time( time_t *time );

lấy calendar thời gian hiện tại (thời điểm từ 01-Jan-1970) nếu thất bại trả về -1 8. strftime()

tên hàm: strftime() định nghĩa: PHP Code:

Page 54: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 54

#include <time.h>

size_t strftime( char *str, size_t maxsize, const char *fmt, struct tm

*time );

convert time format từ time sang str với kiểu format 'fmt' và buffer size 'maxsize' ví dụ lấy thời gian hiện tại PHP Code: #include <stdio.h>

#include <time.h>

int main(void)

{

time_t rawtime;

struct tm *now;

char buffer[80];

time(&rawtime);

now = localtime(&rawtime);

strftime(buffer,80,"time now is %I:%M %p",now);

puts(buffer);

return 0;

} 10. time()

tên hàm: time() định nghĩa: PHP Code: #include <time.h>

time_t time( time_t *time );

lấy calendar thời gian hiện tại (thời điểm từ 01-Jan-1970) nếu thất bại trả về -1 5. Memory

Các hàm sử dụng với Memory 1. calloc 2. free 3. malloc 4. realloc 1. Calloc()

tên hàm : calloc() định nghĩa: PHP Code: #include <stdlib.h>

void* calloc( size_t num, size_t size );

cung cấp khoảng trống cho mảng trong memory. thành công thì giá trị khởi tạo là 0. thất bại trả về NULL

Page 55: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 55

PHP Code: #include <stdlib.h>

#include <stdio.h>

int main(void)

{

int cnt = 0;

int *data;

data = (int*) calloc(4,sizeof(int));

if(data == NULL) exit(1);

for(; cnt < 4; cnt++)

data[cnt] = cnt;

for(cnt = 0; cnt < 4; cnt++) {

printf(" %d",data[cnt]);

}

free(data);

return 0;

} 2. free()

tên hàm: free() định nghĩa: PHP Code: #include <stdlib.h>

void free( void* ptr );

giải phóng bộ nhớ sau khi cấp phát 3. malloc()

tên hàm: malloc() định nghĩa: PHP Code: #include <stdlib.h>

void *malloc( size_t size );

cấp phát bộ nhớ, NULL nếu thất bại

PHP Code: #include <stdlib.h>

#include <stdio.h>

int main(void)

{

char *buffer;

int cnt = 0;

buffer = (char*) malloc(10);

if(buffer == NULL) exit(1);

for(;cnt < 9; cnt++)

buffer[cnt] = rand()%26 + 'a';

buffer[10] = '\0';

printf("Random string: %s\n",buffer);

Page 56: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 56

return 0;

} 4. realloc()

tên hàm: realloc() định nghĩa: PHP Code: #include <stdlib.h>

void *realloc( void *ptr, size_t size );

cung cấp lại bộ nhớ cho con trỏ nào đó, thành công thì trả về khoảng trống mới cấp phát, NULL nếu thất bại 6. Other Standard Functions

Danh sách các hàm chuẩn còn lại: 1. abort 2. assert 3. atexit 4. bsearch 5. exit 6. getenv 7. longjmp 8. qsort 9. raise 10. rand 11. setjmp 12. signal 13. srand 14. system 15. va_arg __________________ 1. abort()

Tên hàm: abort() Định nghĩa: PHP Code:

Page 57: Thư Viện C

Thö Vieän C Y!M: [email protected]

Mr.Vũ Kim Hiếu 57

#include <stdlib.b>

void abort(void);

Dùng để abort process hiện tại. Sẽ trả về tín hiệu SIGABRT cho host environment trong POSIX-platforms, định nghĩa trong signal.h (*nix-like system).

PHP Code: #include <stdio.h>

#include <stdlib.h>

int main(void)

{

FILE *pfile;

pfile = fopen("file.txt","r");

if(pfile == NULL)

{

fputs("error opening file\n",stderr);

abort();

}

fclose(pfile);

return 0;

}

Thân: Mr.Hiếu (ID:freetime719)

Duø ñi heát caû cuoäc ñôøi khoùi buïi… Nhöng cöù tin haïnh phuùc ôû cuoái con ñöôøng..! hjx..!