将数据输入到文件中

85 阅读1分钟
#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。

\

       最后看看文件变成了什么样。

\