用法比较单一,请大家结合代码和注释进行理解
#include "stdio.h" #include "stdlib.h" int main() { FILE *fp; //定义文件指针 char filename[200]; //存放输入的文件名字 char str[200]; //存放一个职工的信息 int i, j; printf("Please enter the file name:\n"); gets(filename); //输入文件名字 fp = fopen(filename, "w"); //以文本模式按只写方式打开文件 if (fp == NULL) //判断文件是否成功打开 { printf("File open failed!\n"); exit(0); } printf("Please input the information of 5 employees:\n"); for(i=0;i<5;i++) //输入五个职工的信息 { gets(str); //输入一个职工的基本信息 fputs(str,fp); /**/将str中的字符串输入到fp文件中** fputc('\n',fp); //一个职工的信息占一行 } fclose(fp); //关闭文件 printf("The employee information was successfully saved in the %s file\n",filename); return 0; }
运行结果如下
总结
fputs()函数功能与以下代码功能类似
for(j=0;str[j]!='\n';j++){ fputc(str[j],fp); //将str里面的内容写入fp文件中 }