在一个txt文件写入500个数字,并读取出来,sprintf sscanf fputs fgets feof

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define MAX 500
void write_file()
{
    int index = 0, num = 0;
    FILE *fp;
    char buf[1024];
    fp = fopen("1.txt","w");
    if(NULL == fp
    {
        perror("write_file fopen");
        return;
    }
    srand((unsigned int) time(NULL));
    for(index = 0; index < MAX; index++)
    {
        num = rand()%100;
        sprintf(buf,"%d\n",num);
        fputs(buf,fp);        
    }    
    fclose(fp);
}

void read_file()
{
    int index = 0, num = 0, a[1024],n = 0;
    FILE *fp;
    char buf[1024];
    fp = fopen("1.txt","r");
    if(NULL == fp
    {
        perror("read_file fopen");
        return;
    }
    while(1)
    {
        fgets(buf,sizeof(buf)-1,fp);
        if(feof(fp))//如果到文件结尾,则跳出循环
        {
            break;            
        }
        sscanf(buf,"%d\n",&num);
        a[index++] = num;        
        
    }
    n = index;
    printf("number is %d\n",n);
    for(index = 0; index < n; index++)
    {
        printf("%d\n",a[index]);        
    }

    fclose(fp);
}

int main()
{
    write_file();
    read_file();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Shayne_Lee/article/details/81458646
今日推荐