用法比较单一,请大家结合代码和注释进行理解
#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); for(j=0;str[j]!='\n';j++){ fputc(str[j],fp); //将str里面的内容写入fp文件中 } fputc('\n',fp); } fclose(fp); //关闭文件 printf("The employee information was successfully saved in the %s file\n",filename); return 0; }
测试结果
![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/6698a277878d4148a29f3f1b4fa949ee.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5L2g5LiN55-l6YGT55qE5Lic5Lic,size_12,color_FFFFFF,t_70,g_se,x_16#pic_center