Q 创建一个后缀名为txt的文件,并向该文件写入一个字符串保存起来。再打开该文件,读出文件中的内容。
注意:所有的I/O函数都定义在 #include<stdio.h> 或者#include"stdio.h"
常用I/O函数:
FILE *fopen(char *filename,char *type); //打开指定路径的文件 int fclose(FILE *fp); //关闭文件 int fread(void *buf,int size,int count,FILE *fp); //读文件函数 int fwrite(void *buf,int size,int count,FILE *fp);//写文件函数
完整程序:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;//fp是一个FILE类型变量,用来保存一个文件指针
char pathName[20],txt1[20]={' '},txt2[20]{' '}; //pathName是字符型的数组首地址,用来保存文件路径
//txt1用来保存输入的字符串,txt2用来保存从文件中读出的字符串,赋值{' '},因为这是C中默认的字符串结束标志
int fileLen; //用来存储输入的字符串长度
printf("type the path name of the file
");
scanf("%s",pathName);
fp=fopen(pathName,"w");//以写的方式打开文件
printf("input a string to this file
");
scanf("%s",txt1); //将字符串写入文件
fileLen=strlen(txt1);
fwrite(txt1,fileLen,1,fp); //将字符串内容写入文件
fclose(fp); //关闭文件
printf("the file has been saved
");
printf("the cintent of the file: %s is
",pathName);
fp=fopen(pathName,"r");//以读的方式打开文件
fread(txt2,fileLen,1,fp);//将文件内容读入缓冲区txt2
printf("%s
",txt2); //将字符串输出到屏幕上
getchar();
return 0;
}
疑惑:发现在下面的语句中不需要&,也可以运行,这是什么情况???
scanf("%s",pathName);
scanf("%s",txt1);