您的位置:首页 > 编程语言 > C语言/C++

黑马程序员——C语言基础——文件读写实战

2015-06-04 21:06 507 查看
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

今天复习的是C语言中另一块比较重要的部分,文件的读写操作。

在复习过后,还是以一道编程题来巩固一下今天的学习成果:

文件的读写操作编程实战:

1.编写一个函数,执行后可以录入一句话(字符串又用户输入)。

2.在每次输入保存后,显示文本中的内容。
具体代码实现如下:
#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[]) {
//定义文件指针
FILE *fp = NULL;//FILE结构体类型的指针
//以写入模式打开一个文件
fp = fopen("fputc.txt", "a+");

//若fopen成功,返回的是文件首地址
//若fopen失败,返回NULL
if(fp == NULL){
printf("打开文件失败!\n");
//非正常退出
exit(1);
}else{
printf("打开文件成功!\n请输入字符:\n");
char ch[1000];
//循环写入文件
fgets(ch, sizeof(ch), stdin);
fputs(ch, fp);
}

//将文件指针重置文件首地址
rewind(fp);
printf("文件中的内容是:\n");
//读取文件
char c = fgetc(fp);
while (c != EOF) {
putchar(c);
//继续读取文件下一个字符
c = fgetc(fp);
}
//关闭文件——保存并退出
fclose(fp);
return 0;
}


编写完成,我自己测试了几次,运行正常。以下是输出结果。
打开文件成功!
请输入字符:
this time I use the fputs function to put this into the file!
文件中的内容是:
This is the last mission
This is aother line!
This is the Three line over there!
This is 4th line over there!
This is 5th line over there!this time I use the fputs function to put this into the file!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: