fprintf()函数用于将一组字符写入文件. 它将格式化的输出发送到流.
fprintf()函数的语法如下:
int fprintf(FILE *stream, const char *format [, argument, ...])
示例:
创建源文件: fprintf-write-file.c,代码如下-
#include
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()函数用于从文件中读取一组字符. 它从文件中读取一个单词,并在文件末尾返回EOF.
fscanf()函数的语法如下:
int fscanf(FILE *stream, const char *format [, argument, ...])
示例:
创建源文件: fscanf-read-file.cc语言fscanf函数,代码如下-
#include
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,姓名和工资.
示例:
创建源文件: storage-employee.c,代码如下-
#include
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文件c语言fscanf函数,其中包含以下内容-
emp.txt
Id= 10010
Name= Maxsu
Salary= 15000.00
¥我要给予奖励
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-159601-1.html