Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Header stdio.h và stdlib.h trong C

stdio.h - Standard Input/Output

Chứa hàm nhập/xuất, file I/O, format.

Hàm chính

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àmMô tả
printfIn ra stdout có format
scanfĐọc từ stdin có format
fprintfIn ra FILE* có format
fscanfĐọc từ FILE* có format
fgetsĐọc dòng từ stream (an toàn)
fputsGhi chuỗi vào stream
getc/getcharĐọc 1 ký tự
putc/putcharGhi 1 ký tự
fopenMở file (r,w,a,rb,wb...)
fcloseĐóng file
fflushXóa buffer output
removeXóa file
renameĐổi tên file
tmpfileTạo file tạm
setbuf/setvbufCấu hình buffer
perrorIn lỗi kèm errno
feof, ferrorKiểm tra EOF/error

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
HàmMô tả
malloc, calloc, realloc, freeQuản lý heap
exit, abort, atexitKết thúc chương trình
atoi, atol, atoll, atofChuỗi → số (cũ, ít an toàn)
strtol, strtod, strtoulChuỗi → số (an toàn, error check)
rand, srandSố ngẫu nhiên pseudo
qsortQuick sort generic
bsearchBinary search generic
abs, labs, llabsGiá trị tuyệt đối
div, ldivChia lấy thương+dư
getenvĐọc biến môi trường
systemChạy lệnh shell