Lập trình C - C fprintf() và fscanf()

C fprintf() and fscanf()


Ghi tập tin : fprintf() 

Hàm fprintf()  thường được sử dụng ghi dữ liệu vào tập tin.

Cú pháp:

int fprintf(FILE *stream, const char *format [, argument, ...])  

Ví dụ:

#include <stdio.h>  
main(){  
   FILE *fp;  
   fp = fopen("file.txt", "w");//Mở tập tin
   fprintf(fp, "Hello file by fprintf...\n");//Ghi dữ liệu vào tập tin
   fclose(fp);//Đóng tập tin  
}  

Đọc tập tin : fscanf() 

Hàm fscanf() thường được sử dụng để đọc dữ liệu từ tập tin. Nó đọc từng từ trong tập tin cho đến khi EOF tập tin

Cú pháp:

int fscanf(FILE *stream, const char *format [, argument, ...])  

Ví dụ:

#include <stdio.h>  
main(){  
   FILE *fp;  
   char buff[255];//creating char array to store data of file  
   fp = fopen("file.txt", "r");  
   while(fscanf(fp, "%s", buff)!=EOF){  
   printf("%s ", buff );  
   }  
   fclose(fp);  
}  

Kết quả:

Hello file by fprintf...

Ví dụ về tập tin: Lưu trữ thông tin nhân viên

Thông tin  nhân viên được người sử dụng nhập từ bàn phím. Sau đó chúng ta sẽ lưu vào tập tin: tên và lương.

#include <stdio.h>  
void main()  
{  
    FILE *fptr;  
    int id;  
    char name[30];  
    float salary;  
    fptr = fopen("D:\\emp.txt", "w+");/*  open for writing */  
    if (fptr == NULL)  
    {  
        printf("File does not exists \n");  
        return;  
    }  
    printf("Enter the id\n");  
    scanf("%d", &id);  
    fprintf(fptr, "Id= %d\n", id);  
    printf("Enter the name \n");  
    scanf("%s", name);  
    fprintf(fptr, "Name= %s\n", name);  
    printf("Enter the salary\n");  
    scanf("%f", &salary);  
    fprintf(fptr, "Salary= %.2f\n", salary);  
    fclose(fptr);  
}  

Kết quả:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Mở tập tin D:\emp.txt chúng ta sẽ thấy thông tin:

Id= 1
Name= sonoo
Salary= 120000