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

Hàm scanf() và fscanf() trong C

scanf() – Đọc từ stdin

Đọc input định dạng từ standard input. Trả về số mục nhập thành công, hoặc EOF nếu lỗi/het file trước khi match bất kỳ conversion nào.

int scanf(const char *format, ...);

Ví dụ

#include <stdio.h>

int main() {
    char s[20];
    printf("Nhap chuoi: ");
    scanf("%s", s);  // Doc mot tu (dung o space)
    printf("Da nhap: %s\n", s);
    return 0;
}

Kết quả

Nhap chuoi: Peter!
Da nhap: Peter!

fscanf() – Đọc từ file stream

Đọc input định dạng từ FILE* stream. Trả về số mục thành công, hoặc EOF.

int fscanf(FILE *stream, const char *format, ...);

Ví dụ

#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[10];
    int year;
    FILE *fp = fopen("file.txt", "w+");
    if (!fp) return 1;
    
    fputs("This is demo text!", fp);
    rewind(fp);
    
    fscanf(fp, "%s", str);  // Doc tu dau tien
    printf("Tu dau tien: %s\n", str);
    
    fclose(fp);
    return 0;
}

Kết quả

Tu dau tien: This

So sánh

Đặc điểmscanf()fscanf()
NguồnstdinFILE* (file, pipe...)
Format stringGiống nhauGiống nhau
Trả vềSố input match / EOFSố input match / EOF
Buffer overflow riskCó (%s không giới hạn)Có (%s không giới hạn)
Cảnh báo bảo mật: scanf("%s", buf) không kiểm tra độ dài -> buffer overflow. Luôn dùng width specifier: scanf("%19s", buf) (buf[20]). Hoặc dùng fgets + sscanf an toàn hơn.