C语言 文件的读写操作

//凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/

 #include<stdio.h>
#include<stdlib.h>
void main(){
int a;
void write();
void read();
while(){
printf("*****************\n");
printf("1.write\n");
printf("2.read\n");
printf("0.exit\n");
printf("*****************\n");
printf("Please choose:");
scanf("%d",&a);
if(a==){
exit();
}
else if(a==){
write();
}
else if(a==){
read();
}
else
printf("input error!\nPlease choose:");
} } void write(){
FILE *fp;
char ch,filename[];
printf("Please input the filename you want to write:");
scanf("%s",filename);
if(!(fp=fopen(filename,"wt+"))){
printf("Cannot open the file!\n");
exit();
} printf("Please input the sentences you want to write:");
ch=getchar();
ch=getchar();
while(ch!=EOF){ //EOF: Ctrl+z
fputc(ch,fp);
ch=getchar();
} fclose(fp); } void read(){
FILE *fp;
char ch,filename[];
printf("Please input the filename you want to read:");
scanf("%s",filename);
if(!(fp=fopen(filename,"r"))){
printf("Cannot open the file!\n");
exit();
} printf("%s 的内容为:",filename);
while(ch!=EOF){ //EOF(end of file): Ctrl+z
ch=fgetc(fp);
putchar(ch);
} fclose(fp);
}

程序运行前的当前目录:

C语言 文件的读写操作

程序运行结果:

C语言 文件的读写操作

当前目录多了一个文件wrr.txt

C语言 文件的读写操作

打开该文件:

C语言 文件的读写操作

里面已经有了刚刚输入的内容:

Hello world!
I am RONGRONG WANG!
My English name is Kailugaji!
Thank you!

上一篇:motan源码解读:注册中心zookeeper(1)


下一篇:MYSQL 慢日志