stdio.h - Standard Input/Output
Chứa hàm nhập/xuất, file I/O, format.
Hàm chính
| Hàm | Mô tả |
printf | In ra stdout có format |
scanf | Đọc từ stdin có format |
fprintf | In ra FILE* có format |
fscanf | Đọc từ FILE* có format |
fgets | Đọc dòng từ stream (an toàn) |
fputs | Ghi chuỗi vào stream |
getc/getchar | Đọc 1 ký tự |
putc/putchar | Ghi 1 ký tự |
fopen | Mở file (r,w,a,rb,wb...) |
fclose | Đóng file |
fflush | Xóa buffer output |
remove | Xóa file |
rename | Đổi tên file |
tmpfile | Tạo file tạm |
setbuf/setvbuf | Cấu hình buffer |
perror | In lỗi kèm errno |
feof, ferror | Kiểm tra EOF/error |
Ví dụ stdio.h
#include <stdio.h>
int main() {
char ch;
printf("Nhập ký tự: ");
ch = getchar(); // hoặc getc(stdin)
printf("Ký tự: ");
putchar(ch); // hoặc putc(ch, stdout)
return 0;
}
stdlib.h - Standard Library
Quản lý bộ nhớ, chuyển đổi, tiện ích, số ngẫu nhiên, tìm kiếm/sắp xếp.
Hàm chính
| Hàm | Mô tả |
malloc, calloc, realloc, free | Quản lý heap |
exit, abort, atexit | Kết thúc chương trình |
atoi, atol, atoll, atof | Chuỗi → số (cũ, ít an toàn) |
strtol, strtod, strtoul | Chuỗi → số (an toàn, error check) |
rand, srand | Số ngẫu nhiên pseudo |
qsort | Quick sort generic |
bsearch | Binary search generic |
abs, labs, llabs | Giá trị tuyệt đối |
div, ldiv | Chia lấy thương+dư |
getenv | Đọc biến môi trường |
system | Chạy lệnh shell |
Ví dụ stdlib.h
#include <stdio.h>
#include <stdlib.h>
int main() {
char str1[] = "53875";
char str2[] = "367587938";
char str3[] = "53875.8843";
long a = atol(str1);
long long b = atoll(str2);
double c = atof(str3);
printf("atol: %ld\n", a);
printf("atoll: %lld\n", b);
printf("atof: %f\n", c);
printf("Random: %d, %d\n", rand(), rand());
return 0;
}
Kết quả
atol: 53875
atoll: 367587938
atof: 53875.884300
Random: 1804289383, 846930886
Lưu ý quan trọng
atoi/atol/atof: Không báo lỗi, trả 0 nếu fail → dùng strtol/strtod
rand(): Chỉ pseudo-random, không dùng cho crypto. C++11: <random>
malloc: Trả void*, C++ cần cast. Check NULL!
qsort/bsearch: Cần comparator function pointer
exit(): Không gọi destructor C++ → tránh trong C++, dùng return hoặc exception