fprintf()
函數(shù)用于將一組字符寫(xiě)入文件。它將格式化的輸出發(fā)送到流。
fprintf()
函數(shù)的語(yǔ)法如下:
int fprintf(FILE *stream, const char *format [, argument, ...])
示例:
創(chuàng)建一個(gè)源文件: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.");
}
執(zhí)行上面示例代碼,得到以下結(jié)果 -
Write to file : file.txt finished.
打開(kāi)filehadling 目錄下,應(yīng)該會(huì)看到一個(gè)文件:file.txt 。
fscanf()
函數(shù)用于從文件中讀取一組字符。它從文件讀取一個(gè)單詞,并在文件結(jié)尾返回EOF
。
fscanf()
函數(shù)的語(yǔ)法如下:
int fscanf(FILE *stream, const char *format [, argument, ...])
示例:
創(chuàng)建一個(gè)源文件: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);
}
執(zhí)行上面示例代碼,得到以下結(jié)果 -
Hello file by fprintf...
文件存取示例:存儲(chǔ)員工信息
下面來(lái)看看一個(gè)文件處理示例來(lái)存儲(chǔ)從控制臺(tái)輸入的員工信息。要存儲(chǔ)雇員的信息有:身份ID,姓名和工資。
示例:
創(chuàng)建一個(gè)源文件: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);
}
執(zhí)行上面示例代碼,得到以下結(jié)果 -
Enter the Emp ID:10010
Enter the name: Maxsu
Enter the salary: 15000
現(xiàn)在從當(dāng)前目錄打開(kāi)文件。將看到有一個(gè)emp.txt文件,其內(nèi)容如下 -
emp.txt
Id= 10010
Name= Maxsu
Salary= 15000.00