将数据输入到文件中
【摘要】
#include <stdio.h>#include <stdlib.h>void write();//声明函数void read();int main()//主函数{ write();//调用函数 read(); return 0;}void write()//实现函数{ FILE *f...
-
#include <stdio.h>
-
#include <stdlib.h>
-
void write();//声明函数
-
void read();
-
int main()//主函数
-
{
-
write();//调用函数
-
read();
-
return 0;
-
}
-
void write()//实现函数
-
{
-
FILE *fp;//文件指针
-
if((fp = fopen("F:\\Codes\\Codeblocks\\C\\FileWriting\\simple.txt","ab+"))==NULL)//文件的路径
-
{
-
printf("Can not open this file!\n");//找不到文件时结束
-
exit(0);
-
}
-
int i,x,n;//i为记录次数的值,x为输入的参数,n为输入的数的总个数
-
printf("please input the number of integers:\n");//总共输入几个数
-
scanf("%d",&n);
-
printf("please input %d integer:\n",n);//输入这几个数
-
for(i = 0; i < n; i++)
-
{
-
scanf("%d",&x);
-
fprintf(fp,"\n");//换行
-
fprintf(fp,"%d",x);//输出到文件中
-
}
-
fclose(fp);
-
}
-
void read()
-
{
-
printf("the file looks as follows:\n");
-
FILE *fp;//文件指针
-
if((fp = fopen("F:\\Codes\\Codeblocks\\C\\FileWriting\\simple.txt","r"))==NULL)//文件的路径
-
{
-
printf("Can not open this file!\n");//找不到文件时结束
-
exit(0);
-
}
-
char ch;
-
ch = fgetc(fp);//获取文件中的字符
-
while(!feof(fp))//判断是否到文件末尾
-
{
-
putchar(ch);//输出字符
-
ch = fgetc(fp);
-
}
-
printf("\n");
-
fclose(fp);
-
}
程序运行结果如下:
这是最初的文件,我是用写字板打开的,如果用记事本打开,后面输入的换行无法体现。
这时,输入0个数,目的要看一下文件里面是不是只有一个1。
输入1一个数2。
输入2个数3,4。
最后看看文件变成了什么样。
文章来源: blog.csdn.net,作者:水坚石青,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/helongqiang/article/details/77408340
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)