C語言fprintf()和fscanf()函數

fprintf()函數用於將一組字符寫入文件。它將格式化的輸出發送到流。

fprintf()函數的語法如下:

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

示例:

創建一個源文件:fprintf-write-file.c,其代碼如下 -

#include <stdio.h>  
main() {
    FILE *fp;
    fp = fopen("file.txt", "w");//opening file  
    fprintf(fp, "Hello file by fprintf...\n");//writing data into file  
    fclose(fp);//closing file  
    printf("Write to file : file.txt finished.");
}

執行上面示例代碼,得到以下結果 -

Write to file : file.txt finished.

打開filehadling 目錄下,應該會看到一個文件:file.txt

讀取文件:fscanf()函數

fscanf()函數用於從文件中讀取一組字符。它從文件讀取一個單詞,並在文件結尾返回EOF

fscanf()函數的語法如下:

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

示例:

創建一個源文件:fscanf-read-file.c,其代碼如下 -

#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);  
}

執行上面示例代碼,得到以下結果 -

Hello file by fprintf...

文件存取示例:存儲員工信息

下面來看看一個文件處理示例來存儲從控制檯輸入的員工信息。要存儲僱員的信息有:身份ID,姓名和工資。

示例:

創建一個源文件:storing-employee.c,其代碼如下 -

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

執行上面示例代碼,得到以下結果 -

Enter the Emp ID:10010
Enter the name: Maxsu
Enter the salary: 15000

現在從當前目錄打開文件。將看到有一個emp.txt文件,其內容如下 -

emp.txt

Id= 10010
Name= Maxsu
Salary= 15000.00