txt文件内的多个数字排序, fprintf, fscanf,

#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;
        fprintf(fp,"%d\n",num); //fprintf一个函数就够了, 相当于sprintf和fputs结合使用。
        //sprintf(buf,"%d\n",num); 
        //fputs(buf,fp);        
    }    
    fclose(fp);
}

void read_file()
{
    int index = 0, num = 0, a[1024],n = 0, i = 0, j = 0;
    FILE *fp;
    char buf[1024];
    fp = fopen("1.txt","r");
    if(NULL == fp
    {
        perror("read_file fopen");
        return;
    }
    while(1)
    {
        fscanf(fp,"%d\n",&num); //使用fscanf提取一步到位,避免使用fgets和sscanf两个函数结合使用。
        a[index++] = num;
        //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 (i=0; i<n-1; i++)
        for(j=0; i<n-i-1; j++)
        {
            if(a[i]>a[j])
            {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
        
    
    fclose(fp);
    
    //以w形式重新打开文件,清空文件,目的是重新按顺序写入
    fp = fopen("1.txt","w");
    for(i=0; i<n; i++)
    {
        fprintf(fp,"%d\n",a[i]); //使用fprintf一步到位,避免使用sprintf和fputs结合使用。
    }
    
    fclose(fp);
}

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

猜你喜欢

转载自blog.csdn.net/Shayne_Lee/article/details/81459842